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
  Too much values to unpack actualpy 3 408 Feb-11-2024, 05:38 PM
Last Post: deanhystad
  need to compare 2 values in a nested dictionary jss 2 794 Nov-30-2023, 03:17 PM
Last Post: Pedroski55
  ValueError - Formatting issue when values enter thousands phillyfa 4 1,112 Apr-20-2023, 06:22 PM
Last Post: phillyfa
  Printing specific values out from a dictionary mcoliver88 6 1,315 Apr-12-2023, 08:10 PM
Last Post: deanhystad
  ValueError: Length mismatch: Expected axis has 8 elements, new values have 1 elements ilknurg 1 5,011 May-17-2022, 11:38 AM
Last Post: Larz60+
  unpack dict menator01 1 1,157 Apr-09-2022, 03:10 PM
Last Post: menator01
  ValueError: not enough values to unpack (expected 4, got 1) vlearner 2 6,277 Jan-28-2022, 06:36 PM
Last Post: deanhystad
Question How to print each possible permutation in a dictionary that has arrays as values? noahverner1995 2 1,695 Dec-27-2021, 03:43 AM
Last Post: noahverner1995
  Getting values from a dictionary brunolelli 5 3,515 Mar-31-2021, 11:57 PM
Last Post: snippsat
  [SOLVED] [geopy] "ValueError: too many values to unpack (expected 2)" Winfried 2 2,835 Mar-30-2021, 07:01 PM
Last Post: Winfried

Forum Jump:

User Panel Messages

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