python two for loops in list comprehension with 2 items

thethiny :

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.

doggie_breath :

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.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=5274&siteId=1