Python Forum

Full Version: Dictionary Comprehension - ValueError: too many values to unpack (expected 2)
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,

Trying to understand dictionary comprehension.
dGro = {"Cabbage": 2, "Carrot":3, "Peas":5, "LadyFinger":1}
print (dGro)
dGroD = {veg:kilo*2 for (veg,kilo) in dGro.items()}

print(dGroD)
The above code works, but when i try to double the kilo of vegetables by 2 with the below code
dGroD = {veg:kilo*2 for (veg,kilo) in dGro if(dGro[kilo] > 1)} 
I get the below error

Error:
ValueError: too many values to unpack (expected 2)
What is wrong with the above code ?

Thanks
kilo is a value, so dGroD[kilo] doesn't make much sense. Try:
dGroD = {veg:kilo*2 for (veg,kilo) in dGro if kilo > 1}
This works as well:
dGroD = {veg: kilo * 2 for (veg, kilo) in dGro.items() if dGro[veg] > 1 }
(Dec-22-2017, 08:59 AM)squenson Wrote: [ -> ]kilo is a value, so dGroD[kilo] doesn't make much sense. Try:
dGroD = {veg:kilo*2 for (veg,kilo) in dGro if kilo > 1}
This works as well:
dGroD = {veg: kilo * 2 for (veg, kilo) in dGro.items() if dGro[veg] > 1 }

Thanks for the help Smile, it works