Reputation: 2273
I have the following dictionaries:
inicio=[
{"market":"oranges", "Valor":104.58},
{"market":"apples","Valor":42.55}
]
I would like to know if it is possible to get value 42.55
if the value of the key market
is apples
.
I was trying something like this:
for d in inicio:
if key['market']='apples':
print(d['Valor'])
Sorry that I do not include further examples, but I am quite new into dealing with dictionaries and not sure what else to try.
Upvotes: 0
Views: 49
Reputation: 17408
Use this code
inicio=[
{"market":"oranges", "Valor":104.58},
{"market":"apples","Valor":42.55}
]
print inicio[1]['Valor']
If you have many items with same apples as market then iterate over the list and check if the key equals apples and then the value. Check this code.
for dictionary in inicio:
if dictionary['market'] == 'apples':
print(dictionary['Valor'])
Upvotes: 0
Reputation: 2592
if you need the lookup only once then the iterative logic you have provided is alright. One optimization can be applied here -
for d in inicio:
if d['market']=='apples':
print(d['Valor'])
break # assuming you only need 1 value
However if you need to rerun this logic again, I would suggest you can iterate once and create a mapping of values.
S o eventually the result may become like {'apples' : 42.55, 'oranges': 104.58}
.
Again assuming there is only one valor for one market.
On the other hand, if there are many valors for each market, you can iterate once and crate a structure like
{'apples' : [42.55, 99.99], 'oranges': [104.58, 99.22]}
Hope it helps.
Upvotes: 0
Reputation: 1634
Your code works. Just replace the "=" with "==" in this line:
if d['market'] =='apples':
Upvotes: 0
Reputation: 5675
In your example d
is the dictionary you're looking for:
for d in inicio:
if d['market']=='apples':
print(d['Valor'])
And use equality operator (==
) instead of assignment (=
)
Upvotes: 2