Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - tuple unpacking in dict comprehension

I'm trying to write a function that turns strings of the form 'A=5, b=7' into a dict {'A': 5, 'b': 7}. The following code snippets are what happen inside the main for loop - they turn a single part of the string into a single dict element.

This is fine:

s = 'A=5'
name, value = s.split('=')
d = {name: int(value)}

This is not:

s = 'A=5'
d = {name: int(value) for name, value in s.split('=')}
ValueError: need more than 1 value to unpack

Why can't I unpack the tuple when it's in a dict comprehension? If I get this working then I can easily make the whole function into a single compact dict comprehension.

like image 894
Benjamin Hodgson Avatar asked Aug 23 '12 15:08

Benjamin Hodgson


2 Answers

In your code, s.split('=') will return the list: ['A', '5']. When iterating over that list, a single string gets returned each time (the first time it is 'A', the second time it is '5') so you can't unpack that single string into 2 variables.

You could try: for name,value in [s.split('=')]

More likely, you have an iterable of strings that you want to split -- then your dict comprehension becomes simple (2 lines):

 splitstrs = (s.split('=') for s in list_of_strings) 
 d = {name: int(value) for name,value in splitstrs }

Of course, if you're obsessed with 1-liners, you can combine it, but I wouldn't.

like image 78
mgilson Avatar answered Sep 21 '22 18:09

mgilson


Sure you could do this:

>>> s = 'A=5, b=7'
>>> {k: int(v) for k, v in (item.split('=') for item in s.split(','))}
{'A': 5, ' b': 7}

But in this case I would just use this more imperative code:

>>> d = {}
>>> for item in s.split(','):
        k, v = item.split('=')
        d[k] = int(v)


>>> d
{'A': 5, ' b': 7}
like image 35
jamylak Avatar answered Sep 21 '22 18:09

jamylak