If I have the following list of items for a shopping store:
shop_list = [{'item': 'apple', 'amount': 10, 'cost': 5},
{'item': 'banana', 'amount': 12, 'cost': 6},
{'item': 'strawberry', 'amount': 8, 'cost': 9}]
So I have several dicts within a list. I want to find out how to get the item dict knowing the item. For example:
def x(item)
#do something to get the dict
print dict
x('apple') #print {'item': 'apple', 'amount': 10, 'cost': 5}
x('banana') #print {'item': 'banana', 'amount': 12, 'cost': 6}
What's the shortest, most efficient way to do this?
If you intend to lookup entries by their 'item'
, then you should consider having a dict
which keys are the 'item'
instead of a list
of dict
.
shop_list = {
'apple': {'amount': 10, 'cost': 5},
'banana': {'amount': 12, 'cost': 6},
'strawberry': {'amount': 8, 'cost': 9}
}
shop_list['banana'] # {'amount': 10, 'cost': 5}
In particular, this makes the lookup O(1) instead of the O(n) required for traversing the list
.
If you cannot update the code that generated the original shop_list
, then you can transform the already existing data with a dict-comprehension.
formatted_shop_list = {product['item']: product for product in shop_list}
def x(shop_list, item): # remove first parameter if you want to use global variable
for i in shop_list:
if i['item'] == item:
return i
Then, you can call this function as:
>>> todays_shop_list = [{'item': 'apple', 'amount': 10, 'cost': 5},
... {'item': 'banana', 'amount': 12, 'cost': 6},
... {'item': 'strawberry', 'amount': 8, 'cost': 9}]
>>> x(todays_shop_list, 'apple')
{'item': 'apple', 'amount': 10, 'cost': 5}
You can try iterating through the list and just extract the dict that matches your shop item:
def shop_item(shop_list, item):
return next((x for x in shop_list if x['item'] == item), None)
# or next(filter(lambda x: x['item'] == item, shop_list), None)
Which works as follows:
>>> shop_list = [{'item': 'apple', 'amount': 10, 'cost': 5},
... {'item': 'banana', 'amount': 12, 'cost': 6},
... {'item': 'strawberry', 'amount': 8, 'cost': 9}]
>>> shop_item(shop_list, 'apple')
{'item': 'apple', 'amount': 10, 'cost': 5}
>>> shop_item(shop_list, 'grape')
None
The above uses next()
with a generator expression to iterate though the list until the condition is met, and returns None
if item is not found.
You can try this:
def x(item):
return [elements for elements in shop_list if elements['item'] == item]
x('apple') #print {'item': 'apple', 'amount': 10, 'cost': 5}
x('banana') #print {'item': 'banana', 'amount': 12, 'cost': 6}
This will return the list item if found
[{'amount': 12, 'cost': 6, 'item': 'banana'}]
and if the result is not found an empty list
will be returned.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.