Reputation: 318
Let's say I have a list of dictionary items:
main_dict = [{'Player': '1', 'position': 'main', 'points': 50},
{'Player': '2', 'position': 'main', 'points': 60},
{'Player': '3', 'position': 'main', 'points': 70},
{'Player': '4', 'position': 'main', 'points': 80},
{'Player': '5', 'position': 'main', 'points': 90}]
I ran some code and got this result:
90
I now want to pull the full dictionary item, from index in the list, using only the value of the points key.
if points == 90:
new_item = (#find item in main_dict[4])
output: {'Player': '5', 'position': 'main', 'points': 90}
How can I pull the full item out of list, using only the unique value of 90?
Upvotes: 0
Views: 172
Reputation: 5531
Yeah I'm gonna assume this is an XY problem and you should just get the item directly, without first finding the points value. For example if you want the player with the most points:
>>> max(main_dict, key=lambda d: d['points'])
{'Player': '5', 'position': 'main', 'points': 90}
Upvotes: 0
Reputation: 6519
filter
built-in should do the trick. If you want to match all items:
new_item = list(filter(lambda x: x['points'] == 90, main_dict))
if you want only the first item which matches:
new_item = next(filter(lambda x: x['points'] == 90, main_dict))
Upvotes: 2
Reputation: 332
Try this:
main_dict = [{'Player': '1', 'position': 'main', 'points': 50},
{'Player': '2', 'position': 'main', 'points': 60},
{'Player': '3', 'position': 'main', 'points': 70},
{'Player': '4', 'position': 'main', 'points': 80},
{'Player': '5', 'position': 'main', 'points': 90}]
def getDict(i):
for retDict in main_dict:
if i == retDict.get('points'):
return(retDict)
print(getDict(90))
Upvotes: 2
Reputation: 161
You can use filter the list to dicts with 'points': 90
using list comprehension:
[inner_dict for inner_dict in main_dict if inner_dict['points'] == 90]
Upvotes: 1