+ 1
Python Lists and Dictionary #Looking for help
""" So , I have a dictionary with many items and keys in it {like supermarket things and price for each of them} and a list[ let's say a shopping list ] , how to iterate through dictionary and search if there is that item in it and to return the key of that item from dictionary ... """ #Example dict= {bread : 4 , banana : 4 , spam : 2, eggs : 5 orange : 6} #and the shopping list shopping_list = [ spam , eggs , banana] #result 2+5+4==11 can someone help me with this?
2 Antworten
+ 2
dict= {"bread" : 4 , "banana" : 4 , "spam" : 2, "eggs": 5, "range" : 6}
shopping_list = [ "spam" , "eggs" , "banana"]
sum=0
for a in dict.keys():
if a in shopping_list:
sum+= dict[a]
print(sum)
+ 1
store_items= {"bread" : 4 , "banana" : 4 , "spam" : 2, "eggs": 5, "range" : 6}
shopping_list = [ "spam" , "eggs" , "banana"]
# list comprehension using dictionary .get() method and the sum function
# might help you too.
print(sum([store_items.get(item_required)for item_required in shopping_list]))