Some languages make you work too hard

Disclaimer: Python is my language of choice for programming, but I have a long Perl history as well.

Coming from Perl, when I find that I must do something simple like taking a string, delimited by pipes, and split it into a hash/dict/associative array/whatever.


mystring = foo|1|bar|2

So I want to take that, and split it into name/value pairs in a mapped data structure. This is trivial in Perl


%map = split /\|/, $mystring;

Now, in my language of choice, this should be simple too, right? Umm, not so much.


map = dict(zip(mystring.split('|')[:-1:2], mystring.split('|')[1::2]))

Geez, if I wanted to type that much, I’d use Java.

To be fair, there are tasks in Python that are trivial and are much harder in Perl, but this is just one of those cases that I find could be made much simpler. Why not just allow dict() to take a list?

Ruby seems to have learned that lesson, even if the syntax is a tad ugly.


msoulier@anton:~$ irb
irb(main):001:0> mystring = "foo|1|bar|2"
=> "foo|1|bar|2"
irb(main):002:0> Hash[*mystring.split('|')]
=> {"foo"=>"1", "bar"=>"2"}

Not a bad medium between the two really. I like Ruby’s design, too bad the docs suck horribly.

One Comment

  1. Posted August 31, 2011 at 10:43 pm | Permalink

    You need the grouper tool from http://docs.python.org/library/itertools.html#recipes

    map = dict(grouper(2, mystring.split(‘|’)))


Post a Comment

Required fields are marked *

*
*