[英]Count the values in list of dictionaries python
如何计算条件匹配的字典列表中的值
test_dicts = [
{
'int_count': 1,
'code': ['500'],
'unique_id': '11',
},
{
'int_count': 1,
'code': ['201'],
'unique_id': '11',
},
{
'int_count': 6,
'code': ['202', '200', '201', '205', '226', '228'],
'unique_id': '11',
},
{
'int_count': 1,
'code': ['303'],
'unique_id': '12',
},
{
'int_count': 5,
'code': ['309', '301', '203', '208', '252'],
'unique_id': '12',
}
]
我期望的 output 基于对具有相同int_count
的项目的unique_id
:
Output = [{'unique_id':11, 'int_count':8}, {'unique_id':12, 'int_count':6}
我会使用defaultdict
来收集计数,然后以所需的格式生成列表:
from collections import defaultdict
counts = defaultdict(int)
for d in test_dicts:
counts[d['unique_id']] += d['int_count']
print([
{'unique_id': unique_id, 'int_count': int_count}
for unique_id, int_count in counts.items()
])
我将进一步简化您的输入,因为有一个有趣的键,并且列表似乎被忽略(不检查唯一性)。
values = [
{'count': 1, 'id': '11'},
{'count': 1, 'id': '11'},
{'count': 6, 'id': '11'},
{'count': 1, 'id': '12'},
{'count': 5, 'id': '12'},
]
然后的问题是按'id
' 和 sum 'count'
分组,例如:
assert res == [{'id':11, 'count':8}, {'id':12, 'count':6}]
您可以通过多种方式执行此操作,但几乎在所有情况下,使用collections.Counter
都会干净且快速。
from collections import Counter
# Get results
counts = Counter()
for val in values:
counts[val['id']] += val['count']
# Change to desired output format
res = [{'id': k, 'count': v} for k, v in counts.items()]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.