Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python two for loops in list comprehension with 2 items

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.

like image 249
thethiny Avatar asked Jan 01 '23 07:01

thethiny


2 Answers

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.

like image 181
doggie_breath Avatar answered Jan 02 '23 20:01

doggie_breath


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.

like image 43
thethiny Avatar answered Jan 02 '23 20:01

thethiny