Reputation: 371
I need to look for a specific value within a variable.
market = {'fruit': [{'fruit_id': '25', 'fruit': 'banana', weight: 1.00}, {'fruit_id': '15', 'fruit': 'apple', weight: 1 .50}, {'fruit_id': '5', 'fruit': 'pear', weight: 2.00}]}
#print(type(market))
<class 'dict'>
How can I find the fruit whose fruit_id is '15'?
Upvotes: 0
Views: 107
Reputation: 71454
If you will need to search for fruits by id more than once, consider creating a dict where the id is the key:
>>> market = {'fruit': [
... {'fruit_id': '25', 'fruit': 'banana', 'weight': 1.00},
... {'fruit_id': '15', 'fruit': 'apple', 'weight': 1.50},
... {'fruit_id': '5', 'fruit': 'pear', 'weight': 2.00}
... ]}
>>>
>>> fruits_by_id = {f['fruit_id']: f for f in market['fruit']}
>>> fruits_by_id['15']
{'fruit_id': '15', 'fruit': 'apple', 'weight': 1.5}
Once you have a dict where a particular piece of data is the key, locating that piece of data by the key is easy, both for you and the computer (it's "constant time", aka effectively instantaneous, to locate an item in a dict by its key, whereas iterating through an entire dict takes an amount of time depending on how big the dict is).
If you aren't constrained in how market
is defined, and your program is going to be looking up items by their id most of the time, it might make more sense to simply make market['fruit']
a dict up front (keyed on id) rather than having it be a list. Consider the following representation:
>>> market = {'fruit': {
... 25: {'name': 'banana', 'weight': 1.00},
... 15: {'name': 'apple', 'weight': 1.50},
... 5: {'name': 'pear', 'weight': 2.00}
... }}
>>> market['fruit'][15]
{'name': 'apple', 'weight': 1.5}
Upvotes: 1
Reputation: 4779
You can iterate over the value of fruit
from markets
dict and search.
for fr in market['fruit']:
if fr['fruit_id'] == '15':
ans = fr
print(ans)
ans = {'fruit_id': '15', 'fruit': 'apple', 'weight': 1.50}
Upvotes: 1
Reputation: 120409
In addition to the comments, you can create a function to search in your market
dictionary:
market = {'fruit': [{'fruit_id': '25', 'fruit': 'banana', 'weight': 1.0},
{'fruit_id': '15', 'fruit': 'apple', 'weight': 1.5},
{'fruit_id': '5', 'fruit': 'pear', 'weight': 2.0}]}
def search_by_id(fruit_id):
for fruit in market['fruit']:
if fruit['fruit_id'] == fruit_id:
return fruit['fruit']
How to use it:
>>> search_by_id('15')
'apple'
>>> search_by_id('5')
'pear'
Upvotes: 1