Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

Python dict to perl hash

by garg10may (Initiate)
on Mar 30, 2015 at 11:32 UTC ( [id://1121802]=perlquestion: print w/replies, xml ) Need Help??

garg10may has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks, I want to convert a python dict to perl hash. Is there a better/easy way to do this than below.
use Data::Dumper; sub rot13 { my $x = "'a':'n', 'b':'o', 'c':'p', 'd':'q', 'e':'r', 'f':'s', 'g' +:'t', 'h':'u', 'i':'v', 'j':'w', 'k':'x', 'l':'y', 'm':'z', 'n':'a', 'o':'b', +'p':'c', 'q':'d', 'r':'e', 's':'f', 't':'g', 'u':'h', 'v':'i', 'w':'j', +'x':'k', 'y':'l', 'z':'m', 'A':'N', 'B':'O', 'C':'P', 'D':'Q', 'E':'R', +'F':'S', 'G':'T', 'H':'U', 'I':'V', 'J':'W', 'K':'X', 'L':'Y', 'M':'Z', +'N':'A', 'O':'B', 'P':'C', 'Q':'D', 'R':'E', 'S':'F', 'T':'G', 'U':'H', +'V':'I', 'W':'J', 'X':'K', 'Y':'L', 'Z':'M'"; $x =~ s/['\s+]//g; my %hash = split /[:,]/, $x; print Dumper\%hash; } rot13();

Replies are listed 'Best First'.
Re: Python dict to perl hash
by hdb (Monsignor) on Mar 30, 2015 at 12:00 UTC

    Use JSON:

    use strict; use warnings; use Data::Dumper; use JSON; sub rot13 { my $x = "'a':'n', 'b':'o', 'c':'p', 'd':'q', 'e':'r', 'f':'s', 'g' +:'t', 'h':'u', 'i':'v', 'j':'w', 'k':'x', 'l':'y', 'm':'z', 'n':'a', 'o':'b', + 'p':'c', 'q':'d', 'r':'e', 's':'f', 't':'g', 'u':'h', 'v':'i', 'w':'j', + 'x':'k', 'y':'l', 'z':'m', 'A':'N', 'B':'O', 'C':'P', 'D':'Q', 'E':'R', + 'F':'S', 'G':'T', 'H':'U', 'I':'V', 'J':'W', 'K':'X', 'L':'Y', 'M':'Z', + 'N':'A', 'O':'B', 'P':'C', 'Q':'D', 'R':'E', 'S':'F', 'T':'G', 'U':'H', + 'V':'I', 'W':'J', 'X':'K', 'Y':'L', 'Z':'M'"; $x=~s/'/"/g; my %hash = %{ from_json "{$x}" }; print Dumper \%hash; } rot13();
Re: Python dict to perl hash
by BrowserUk (Patriarch) on Mar 30, 2015 at 14:15 UTC

    Why use a hash when tr does the job so simply and efficiently?:

    sub rot13{ my $text = shift; $text =~ tr[a-zA-Z][n-za-mN-ZA-M]; return $text };; $msg = 'The quick brown fox jumps over the lazy dog. And then runs awa +y.';; print rot13( $msg );; Gur dhvpx oebja sbk whzcf bire gur ynml qbt. Naq gura ehaf njnl. print rot13( rot13( $msg ) );; The quick brown fox jumps over the lazy dog. And then runs away.

    With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority". I'm with torvalds on this
    In the absence of evidence, opinion is indistinguishable from prejudice. Agile (and TDD) debunked
Re: Python dict to perl hash
by Corion (Patriarch) on Mar 30, 2015 at 12:05 UTC

    If the problem is specific to rot13, there also is Rot13 Challenge. If the problem is more general, I would export from Python to JSON and then import the JSON to Perl.

Re: Python dict to perl hash
by dave_the_m (Monsignor) on Mar 30, 2015 at 14:05 UTC
    If you're just looking for a way to create, in a Perlish way, a hash that does rot13 character mappings, then try something like this:
    my %rot13; @rot13{'a'..'z'} = ('n'..'z','a'..'m');

    Dave.

Re: Python dict to perl hash
by Tux (Canon) on Mar 30, 2015 at 11:46 UTC

    $x =~ s/['\s+]//g; is most likely not doing what you think it does. You might mean s{(?:'|\s+)}{}, but what if any of the dict entries has a quote, a comma of whitespace in general?


    Enjoy, Have FUN! H.Merijn
Re: Python dict to perl hash
by Anonymous Monk on Mar 30, 2015 at 11:41 UTC

    Given only your example, that looks fine. But if the input dict gets more complicated, the method may break, so it's not a good general-purpose solution. If this is a one-time thing, why not replace my $x = ... with the Dumper output, so you've got the hash written directly in Perl? Or, are you looking for a general solution?

      I think replacing this:

      $x =~ s/['\s+]//g; my %hash = split /[:,]/, $x;

      with this:

      $x =~ s/'\s*:\s*'/' => '/g; my %hash = %{ eval "{$x}" };

      would make it less breakable (but still breakable if and keys or values contained something like "' : '").

      But I copied that dict from somewhere and need to convert it to hash to work upon it. I cannot have dumper output without the input. So yes you can say in general.

        If you need THAT hash, here it is

        my %hash = map { chr(65+$_)=>chr(65+($_+13)%26), chr(97+$_)=>chr(97+($_+13)%26)} 0..25;
        But I copied that dict from somewhere ...

        It's still unclear to me whether you're talking about only this one dict? Or whether you have a bunch of different dicts that you need to translate to Perl?

        The code you showed produces an output: a hash(ref) in Perl's own syntax. Copy that output back into your Perl script, replacing your current hash definition, and you'll have a hash defined in pure Perl.

        sub rot13 { my %hash = ( a=>"n", b=>"o", c=>"p", ... ); ... }
Re: Python dict to perl hash
by einhverfr (Friar) on Mar 30, 2015 at 14:12 UTC

    Not sure if this is helpful or not but for rot13, there is Crypt::Rot13 on CPAN. Just a reminder to check CPAN for everything first....

    Now my code would be simpler:

    my $x = ... my %hash = map { s/(^'|'$)// } split /(:|, )/ $x;

    That assumes you want something like

    %x = ( a => 'n', b => 'o', ...);

    But it also looks trivial to convert this to valid json and use that module

    Update: On second thought that above approach won't work. I think you will need to do something like:

    my $x = ... my %hash = map { my $v = $_; $v =~ s/(^'|'$)//; $v} split /(:|, )/ + $x;

      This is not on the CPAN: Crypt::Rot26 but it provides twice the security that Rot13 offers.

      jeffa

      L-LL-L--L-LL-L--L-LL-L--
      -R--R-RR-R--R-RR-R--R-RR
      B--B--B--B--B--B--B--B--
      H---H---H---H---H---H---
      (the triplet paradiddle with high-hat)
      
        I am afraid it is on CPAN. If you use the module 'M' from CPAN, your assignment operator will automatically be upgraded with ROT26 support!
Re: Python dict to perl hash
by GotToBTru (Prior) on Mar 30, 2015 at 14:49 UTC

    Several clever solutions to the specific problem of rot13, but useless in terms of the more general problem of converting a Python dict to a Perl hash! I've heard of an XY problem; are these XY solutions? ;)

    Dum Spiro Spero
      are these XY solutions? ;)

      Kind depends upon the reason for having to do a conversion in the first place doesn't it?

      Unless there is a generic need to convert python dicts to Perl hashes?


      With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
      Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
      "Science is about questioning the status quo. Questioning authority". I'm with torvalds on this
      In the absence of evidence, opinion is indistinguishable from prejudice. Agile (and TDD) debunked
Re: Python dict to perl hash
by Tux (Canon) on Mar 31, 2015 at 14:23 UTC
    use strict; use warnings; use Inline Python => <<'EOP'; def rot13(): return dict({ 'a':'n', 'b':'o', 'c':'p', 'd':'q', 'e':'r', 'f':'s', 'g':'t', + 'h':'u', 'i':'v', 'j':'w', 'k':'x', 'l':'y', 'm':'z', 'n':'a', 'o':'b', + 'p':'c', 'q':'d', 'r':'e', 's':'f', 't':'g', 'u':'h', 'v':'i', 'w':'j', + 'x':'k', 'y':'l', 'z':'m', 'A':'N', 'B':'O', 'C':'P', 'D':'Q', 'E':'R', + 'F':'S', 'G':'T', 'H':'U', 'I':'V', 'J':'W', 'K':'X', 'L':'Y', 'M':'Z', + 'N':'A', 'O':'B', 'P':'C', 'Q':'D', 'R':'E', 'S':'F', 'T':'G', 'U':'H', + 'V':'I', 'W':'J', 'X':'K', 'Y':'L', 'Z':'M'}) EOP my $hash = rot13 ();

    Enjoy, Have FUN! H.Merijn
      What happens in the general case with nested data structures?

      This looks like only returning a flat list...

      Or am I undervaluing the power of inline python?

      update

      Sorry, I didn't realize that $hash IS a scalar (I read %hash), that should answer the question already.

      Never mind. :)

      Cheers Rolf
      (addicted to the Perl Programming Language and ☆☆☆☆ :)

      PS: Je suis Charlie!

Re: Python dict to perl hash
by LanX (Saint) on Mar 31, 2015 at 11:23 UTC

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://1121802]
Front-paged by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others admiring the Monastery: (7)
As of 2024-04-23 10:05 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found