9

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.

1 Answer 1

15

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'}
Sign up to request clarification or add additional context in comments.

1 Comment

This is so good, thank you!. Looks like I've tried to do it too in complicated way.

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.