python - 将 [{str :int}, {str :int}, ... ] 的字典列表转换为 {str:int} 的单个字典

标签 python dictionary counter mean flatten

给定这样的数据结构:

[{'a':1, 'b': 2}, {'c':3 }, {'a':4, 'c':9}, {'d':0}, {'d': 0, 'b':6}]

目标是解析数据以产生:

{'a': 2.5, 'b': 4, 'c': 6, 'd': 0}

通过做:

  • 累积每个唯一键的值,
  • 平均每个键的值

实现上述数据处理的简单方法是什么?


我已经尝试了以下并且有效:

from collections import defaultdict
from statistics import mean


x = [{'a':1, 'b': 2}, {'c':3 }, {'a':4, 'c':9}, {'d':0}, {'d': 0, 'b':6}]

z = defaultdict(list)

for y in x:
    for k, v in y.items():
        z[k].append(v)

output = {k: mean(v) for k,v in z.items()}

但是是否有更简单的方法来实现相同的数据解析?也许使用 collections.Counter 或其他东西?

最佳答案

如果你想要一些带有计数器的东西,你可以分别计算键和值,然后像这样计算平均值:

original = [{'a':1, 'b': 2}, {'c':3 }, {'a':4, 'c':9}, {'d':0}, {'d': 0, 'b':6}]

sum_counter = dict(sum([Counter(x) for x in original], Counter()))
count_counter = dict(sum([Counter(x.keys()) for x in original], Counter()))
final = {k: sum_counter.get(k,0)/count_counter[k] for k in count_counter}

print(final)

输出:

{'a': 2.5, 'b': 4.0, 'c': 6.0, 'd': 0.0}

编辑: 我有另一个想法,它可能是解决您问题的更简单的方法(事实证明它也快得多)。这个想法是遍历您的字典列表并创建一个新字典,其中为每个键保存值的总和和出现次数。之后,我们可以通过将键的两个值相除来简单地计算每个键的平均值。

from collections import defaultdict

original = [{'a':1, 'b': 2}, {'c':3 }, {'a':4, 'c':9}, {'d':0}, {'d': 0, 'b':6}]

ddict = defaultdict(lambda: [0,0])

for dictionary in original:
    for key in dictionary:
        ddict[key][0] += dictionary[key]
        ddict[key][1] += 1        
        
final = {k: ddict[k][0]/ddict[k][1] for k in ddict}
print(final)

输出还是一样:

{'a': 2.5, 'b': 4.0, 'c': 6.0, 'd': 0.0}

关于python - 将 [{str :int}, {str :int}, ... ] 的字典列表转换为 {str:int} 的单个字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71128953/

相关文章:

Python Counter keys() 返回值

python - 递归后重置计数器

r - 创建具有多个变量的计数器

javascript - 在 javascript/node 或其他干净的方法中映射

python - 从字典列表值中获取值

python - 为什么字典花费的时间比在 python 中设置的时间少?

python - Tensorflow 2.0具体函数structured_input_signature返回值

python - 计算 pandas 中每组的数值差异

python - 如何比较列表中的项目是否与另一个列表中的项目具有相同的值和位置? Python 2.7

python - 4 人锦标赛安排,Python