Reputation: 7
Given following information:
item : Apple
price : 120
item : Orange
price : 90
item : Banana
price : 60
What data structure should be used to store the above data in python. How to get the price of banana using that data structure?
My Approach: I thought it can be stored using list of dictionary.
List = [{'item':'Apple','price':120},{'item':'Orange','price':90},{'item':'Banana','price':60}]
#Retrieving price of banana
for i in range(len(List)):
if List[i]['item']=='Banana':
price = List[i]['price']
print(price)
What is wrong with the above approach? Or is there any better approach for the above problem?
Upvotes: 0
Views: 160
Reputation: 1121206
You don't need a list here; you can store all your items in one dictionary, mapping item name to price:
item_prices = {
'Apple': 120,
'Orange': 90,
'Banana': 60,
}
print(item_prices['Banana'])
Now you don't need a loop anymore. And testing if an item is present is as easy as if 'Banana' in item_prices:
, no full scan required.
Upvotes: 5