簡體   English   中英

在Python中,如何將不同的項目添加到另一個字典的字典列表中?

[英]In Python, how to add distinct items to a list of dicts from another dict?

在Python中,原始字典列表如下:

orig = [{'team': 'team1', 'other': 'blah', 'abbrev': 't1'},
        {'team': 'team2', 'other': 'blah', 'abbrev': 't2'},
        {'team': 'team3', 'other': 'blah', 'abbrev': 't3'},
        {'team': 'team1', 'other': 'blah', 'abbrev': 't1'},
        {'team': 'team3', 'other': 'blah', 'abbrev': 't3'}]

需要獲得一個僅包含團隊和縮寫的新字典列表,如下所示:

new = [{'team': 'team1', 'abbrev': 't1'},
       {'team': 'team2', 'abbrev': 't2'},
       {'team': 'team3', 'abbrev': 't3'}]

dict鍵是唯一的,您可以利用:

teamdict = dict([(data['team'], data) for data in t])
new = [{'team': team, 'abbrev': data['abbrev']} for (team, data) in teamdict.items()]

不禁暗示,字典可能是您選擇的數據結構的開始。

哦,我不知道dict()對列表中有幾個相同鍵的事實有何反應。 在這種情況下,您可能需要構造較少pythonesque的字典:

teamdict={}
for data in t:
  teamdict[data['team']] = data

隱式覆蓋雙重條目

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM