简体   繁体   中英

How can I do comparison in List of dictionaries for key values?

I have this list of dictionary below. What i want is to search for same "alias" and add their score to combine them into a single dictionary and make a cleaner list.

d=[{"alias": "2133232", "score": 144}, {"alias": "u234243", "score": 34}, {"alias": "u234243", "score": 34},{"alias": "2133232", "score": 14}, {"alias": "u234243", "score": 4}, {"alias": "u234243", "score": 344}]

Output should look like:

`[{"alias": "2133232", "score": 158}, {"alias": "u234243", "score": 416}]`

Python 2.5:

from collections import defaultdict 

h = defaultdict(int)
for i in d:
    h[i['alias']] += i['score']

In Python 3.1+:

import collections
res = collections.Counter()
for dct in d:
   res[dct['alias']] += dct['score']
print(repr(res))

Before 3.1, you can either use this Counter class , replace Counter() with collections.defaultdict(int) (2.5+), or the following:

res = {}
for dct in d:
   alias = dct['alias']
   if alias not in res:
      res[alias] = 0
   res[alias] += dct['score']
print(repr(res))
from itertools import groupby
from operator import itemgetter
dict(((u, sum(row['score'] for row in rows)) for u, rows in
    groupby(sorted(d, key=itemgetter('alias')), key=itemgetter('alias'))))
# {'2133232': 158, 'u234243': 416}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM