tags:

views:

58

answers:

1

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'}]
+2  A: 

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

Nicolas78
+1. By the way the first line gives a syntax error. You might want to lose that last `]`.
Manoj Govindan
thx. but shouldn't I add another one, rather? or can I put the list comprehension in there directly without further brackets?
Nicolas78
This does it, but I think there is an error in the teamdict code. Should be:teamdict = dict([(data['team'], data) for data in orig])Thank you.
simi
ok, corrected it for the record
Nicolas78
The second part works well also. Thank you for both options. I need to learn more data structures.
simi