Python Forum
Dictionary Comprehension - ValueError: too many values to unpack (expected 2)
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Dictionary Comprehension - ValueError: too many values to unpack (expected 2)
#1
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
Reply
#2
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 }
Reply
#3
(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
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  I'm assuming you're asking about accessing nested dictionary keys and values in Pytho DavidSah 0 579 Dec-18-2025, 01:54 AM
Last Post: DavidSah
Question [SOLVED] Access keys and values from nested dictionary? Winfried 4 913 Nov-17-2025, 11:47 AM
Last Post: Winfried
  cannot unpack non-iterable int object in urllib3/util/wait.py", line 85, ping_chen_ibm_us 2 931 Aug-01-2025, 02:05 PM
Last Post: ping_chen_ibm_us
  Replace values in Yaml file with value in dictionary PelleH 1 3,817 Feb-11-2025, 09:51 AM
Last Post: alexjordan
  DEC pack, unpack and disk-images Curbie 32 10,791 Aug-23-2024, 03:37 PM
Last Post: Curbie
Question Using Lists as Dictionary Values bfallert 8 3,937 Apr-21-2024, 06:55 AM
Last Post: Pedroski55
  Too much values to unpack actualpy 3 2,143 Feb-11-2024, 05:38 PM
Last Post: deanhystad
  need to compare 2 values in a nested dictionary jss 2 2,973 Nov-30-2023, 03:17 PM
Last Post: Pedroski55
  ValueError - Formatting issue when values enter thousands phillyfa 4 3,019 Apr-20-2023, 06:22 PM
Last Post: phillyfa
  Printing specific values out from a dictionary mcoliver88 6 3,856 Apr-12-2023, 08:10 PM
Last Post: deanhystad

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020