簡體   English   中英

計算字典列表 python 中的值

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

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM