ValueError: too many values to unpack in the Python Dictionary for Moon

Asked 2 years ago, Updated 2 years ago, 57 views

n = int(input('Enter number of products : '))
prod = {}
for i in range(n):
    ProductName = input('Enter product name : ')
    ProductPrice = int(input('Enter its price : '))
    prod[ProductName] = ProductPrice

print(prod)        #prod = {'prod1': 100, 'prod2': 200, 'prod3': 300}



ProductName = input('enter price')
print(ProductName)

for ProductName, prod[ProductPrice] in prod:
    if prod[ProductName] < ProductName:
    print(ProductName)

When I enter 200 in ProductName, I want to print a prod1 that has a value of 100 less than 200, but I get an error. I ask for your help me.

Traceback (most recent call last):
File "C: Grade 2 File/Construction Plant Introduction/#11.Dictionaries_Exercise/#2.py", line 28, in <module>
for ProductName, prod[ProductPrice] in prod:
ValueError: too many values to unpack (expected 2)

python dictionary

2022-09-21 10:41

2 Answers

dictionary returns a key in for loop.
If you want to use both key and value at the same time, use it as below.

d = {'a': 1, 'b': 2, 'c': 3}
for k in d:
    print(k)  # 'a', 'b', 'c'
for k, v in d.items():
    print((k, v))  # ('a', 1), ('b', 2), ('c', 3)


2022-09-21 10:41

prod= {'prod1': 100, 'prod2': 200, 'prod3': 300}
_input = 200
for key in prod: #
    if prod[key] < _input:
        print(key)

In #, prod has the dictionary key value prod1, prod2, prod3 so it cannot be unpacked with two.


2022-09-21 10:41

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.