繁体   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