[英]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.