简体   繁体   English

如何在键值的字典列表中进行比较?

[英]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: Output 应如下所示:

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

Python 2.5: Python 2.5:

from collections import defaultdict 

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

In Python 3.1+:在 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:在 3.1 之前,您可以使用此计数器 class ,将Counter()替换为collections.defaultdict(int) (2.5+),或以下内容:

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}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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