开发者

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

开发者 https://www.devze.com 2023-01-13 01:04 出处:网络
In Python, the original dict list is as follows: orig = [{\'team\': \'team1\', \'other\': \'blah\', \'abbrev\': \'t1\'},

In Python, the original dict list is as follows:

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'}]

Need to get a new dict list of just team and abbrev but of distinct teams into a list开发者_高级运维 like this:

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


dict keys are unique, which you can exploit:

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

Can't help to suggest that a dict might be your data structure of choice to begin with.

Oh, I don't know how dict() reacts to the fact that there are several identical keys in the list. You may have to construct the dictionary less pythonesque in that case:

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

implicitly overriding double entries

0

精彩评论

暂无评论...
验证码 换一张
取 消