[英]How to access the dictionary from a list of dictionaries using one key/value pair of the dictionary that I want to fetch
[英]How can I pull one item, from a list of dictionary items, using a single key:value pair?
假设我有一个字典项目列表:
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}]
我运行了一些代码并得到了这个结果: 90
我现在想从列表中的索引中提取完整的字典项,仅使用 points 键的值。
if points == 90:
new_item = (#find item in main_dict[4])
output: {'Player': '5', 'position': 'main', 'points': 90}
如何仅使用唯一值 90 将整个项目从列表中拉出?
尝试这个:
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
应该可以解决问题。 如果要匹配所有项目:
new_item = list(filter(lambda x: x['points'] == 90, main_dict))
如果您只想要第一个匹配的项目:
new_item = next(filter(lambda x: x['points'] == 90, main_dict))
您可以使用列表理解将列表过滤为具有'points': 90
字典:
[inner_dict for inner_dict in main_dict if inner_dict['points'] == 90]
是的,我会假设这是一个 XY 问题,您应该直接获取该项目,而无需先找到积分值。 例如,如果您想要得分最多的玩家:
>>> max(main_dict, key=lambda d: d['points'])
{'Player': '5', 'position': 'main', 'points': 90}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.