简体   繁体   中英

How can I pull one item, from a list of dictionary items, using a single key:value pair?

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?

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))

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))

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]

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}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM