Photon Light
Photon Light

Reputation: 777

Create dictionary from splitted strings from list of strings

I feel that this is very simple and I'm close to solution, but I got stacked, and can't find suggestion in the Internet.
I have list that looks like:

my_list = ['name1@1111', 'name2@2222', 'name3@3333']  

In general, each element of the list has the form: namex@some_number.
I want to make dictionary in pretty way, that has key = namex and value = some_number. I can do it by:

md = {}
for item in arguments:
    md[item.split('@')[0]] = item.split('@')[1]  

But I would like to do it in one line, with list comprehension or something. I tried do following, and I think I'm not far from what I want.

md2 = dict( (k,v) for k,v in item.split('@') for item in arguments )

However, I'm getting error: ValueError: too many values to unpack. No idea how to get out of this.

Upvotes: 9

Views: 171

Answers (1)

Cory Kramer
Cory Kramer

Reputation: 118021

You actually don't need the extra step of creating the tuple

>>> my_list = ['name1@1111', 'name2@2222', 'name3@3333']
>>> dict(i.split('@') for i in my_list)
{'name3': '3333', 'name1': '1111', 'name2': '2222'}

Upvotes: 15

Related Questions