Pregunta

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.

¿Fue útil?

Solución

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.

Otros consejos

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}

Some people tend to believe you'll go to hell for using eval, but...

s = 'A=5, b=7'
eval('dict(%s)' % s)

Or better, to be safe (thanks to mgilson for pointing it out):

s = 'A=5, b=7'
eval('dict(%s)' % s, {'__builtins__': None, 'dict': dict})

How about this code:

a="A=5, b=9"
b=dict((x, int(y)) for x, y in re.findall("([a-zA-Z]+)=(\d+)", a))
print b

Output:

{'A': 5, 'b': 9}

This version will work with other forms of input as well, for example

a="A=5 b=9 blabla: yyy=100"

will give you

{'A': 5, 'b': 9, 'yyy': 100}
>>> strs='A=5, b=7'

>>> {x.split('=')[0].strip():int(x.split('=')[1]) for x in strs.split(",")}
{'A': 5, 'b': 7}

for readability you should use normal for-in loop instead of comprehensions.

strs='A=5, b=7'
dic={}
for x in strs.split(','):
  name,val=x.split('=')
  dic[name.strip()]=int(val)

See mgilson answer to why the error is happening. To achieve what you want, you could use:

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

To account for spaces, use .strip() as needed (ex.: x.strip().split('=',1)).

How about this?

>>> s
'a=5, b=3, c=4'
>>> {z.split('=')[0].strip(): int(z.split('=')[1]) for z in s.split(',')}
{'a': 5, 'c': 4, 'b': 3}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top