[英]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.