Take apart the card int & # 8594; list from string

This should be a pretty straightforward python question, but I'm stuck getting the syntax right.

Let's say I have a line:

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

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

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

How to do it?

I can figure out how to do this using nested loops, but it would be great to just do it on one line.

Thank!

+3
source share
1 answer

Here is one approach:

dict((k, v.split(',')) for k,v in (x.split(':') for x in s.split('::')))
+8
source

Source: https://habr.com/ru/post/1769233/


All Articles