3

This should be a fairly straight forward python question, but I'm getting stuck getting the syntax right.

Let's say I have a string:

"1:a,b,c::2:e,f,g::3:h,i,j"

and I want to convert this to a map like so:

{'1': ['a', 'b', 'c'], '2': ['e', 'f', 'g'], '3': ['h', 'i', 'j']}

How would this be done?

I can figure out how to do it using nested for loops, but would be cool to just do it in a single line.

Thanks!

1
  • hint: have a look at string's split method which you can use to break your input string into chunks that you can further work on (perhaps with more calls to split) Commented Oct 12, 2010 at 20:38

1 Answer 1

8

Here's one approach:

dict((k, v.split(',')) for k,v in (x.split(':') for x in s.split('::')))
Sign up to request clarification or add additional context in comments.

4 Comments

Horrible names, but otherwise perfect, +1
@delnan: not quite perfect, use of list() is redundant
@John Machin: Thanks for pointing that out. I wasn't sure if split returns a list in all versions of Python so was playing it safe. But I checked now and it seems that it always does. Fixed now. :)
I wasn't sure either if split returned a list. They made nearly everything an iterator in Python 3 (which is a good thing) ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.