简体   繁体   中英

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.

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'}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM