Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 378
Photon Light Avatar asked Dec 16 '15 18:12

Photon Light


1 Answers

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'}
like image 98
Cory Kramer Avatar answered Oct 20 '22 14:10

Cory Kramer