繁体   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