I'm trying to comprehend two loops in one line with 2 variables, however it is always returning one variable and I don't seem to understand the reason behind it. My code is as follow:
text = ['hello, hi', 'goodbye, bye', 'how do you do, howdy']
mapped = {x:y for string in text for x, y in string.split(',')}
The error I'm getting:
ValueError: too many values to unpack (expected 2)
How can I adjust my line so that it returns 2 variables instead of one? Or is it just not possible?
I understand that expanded it looks as follows:
for string in text:
for x, y in string.split(','):
mapped[x] = y
I don't understand where I'm going wrong.
Look carefully at the order of operations that you really want - and I think you're just missing some brackets:
text = ['hello, hi', 'goodbye, bye', 'how do you do, howdy']
mapped = {x:y for x, y in [string.split(',') for string in text]}
Works for me.
I found a different way to achieve the same result, but without using double comprehension (which defeats the point in this question). I'm sharing it in case someone wants to know.
dict(string.split(',') for string in text)
since x:y for x, y
is redundant it can simply be omitted.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With