From user input, I can make a list. It is the intention for this list to be cross-checked with the dictionary and the corresponding value to be printed in another list.
Upon inputting "food" twice, a type-error of unhashable type: "list"
What can I do to solve this problem? Either through a change in ordering or the use of novel functions? This is my code:
grocery_market = {"food": 2}
shopping_list = []
max_shop_list = 2
while len(shopping_list) < max_shop_list:
item = input("Add an item: ")
shopping_list.append(item)
print(shopping_list)
print(grocery_market[shopping_list])
CodePudding user response:
Im not sure what "printed in another list" means.
But you can use lost comprehension with if statement:
print([item for item in shopping_list if item in grocery_market])
Or dict comprehension:
print({item: value for item, value in grocery_market.items() if item in shopping_list})
CodePudding user response:
I think this is what you are looking for:
grocery_market = {"food": 2}
shopping_list = []
max_shop_list = 2
while len(shopping_list) < max_shop_list:
item = input("Add an item: ")
shopping_list.append(item)
print(shopping_list)
both = [] # Create a dictionary to put our results in
for item in shopping_list:
if item in list(grocery_market.keys()): # Check if the item exists in the grocery market
both.append(grocery_market[item]) # Add the item to the dictionary if found in both
print(both) # Print out the results
If you want a dictionary do
both = {}
for item in shopping_list:
if item in list(grocery_market.keys()): # Check if the item exists in the grocery market
both[item] = grocery_market[item] # Add the item to the dictionary if found in both
print(both)
(this was the original answer)
CodePudding user response:
Seems like you want to look up the value of each item in the list. Using shopping_list_values = [grocery_market[item] for item in shopping_list]
will get you that.
grocery_market = {"food": 2}
shopping_list = []
max_shop_list = 2
while len(shopping_list) < max_shop_list:
item = input("Add an item: ")
shopping_list.append(item)
print(shopping_list)
print([grocery_market[itm] for itm in shopping_list])
This prints
Add an item:
food
['food']
Add an item:
food
['food', 'food']
[2, 2]