Dictionary Comprehension - ValueError: too many values to unpack (expected 2) - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Dictionary Comprehension - ValueError: too many values to unpack (expected 2) (/thread-7131.html) |
Dictionary Comprehension - ValueError: too many values to unpack (expected 2) - samRddhi - Dec-22-2017 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 What is wrong with the above code ?Thanks RE: Dictionary Comprehension - ValueError: too many values to unpack (expected 2) - squenson - Dec-22-2017 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 } RE: Dictionary Comprehension - ValueError: too many values to unpack (expected 2) - samRddhi - Dec-22-2017 (Dec-22-2017, 08:59 AM)squenson Wrote: Thanks for the help , it works |