Python - tuple unpacking in dict comprehension

Benjamin Hodgson picture Benjamin Hodgson · Aug 23, 2012 · Viewed 10k times · Source

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.

Answer

mgilson picture mgilson · Aug 23, 2012

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.