python - 对外部键进行分组后求内部字典键的平均值

标签 python dictionary

我有一个嵌套字典,例如;

dictionary =  {'cat_1' : {'age' : 5, 'height' : 15}, 'cat_2' :  {'age' : 1, 'height' : 7}, 'dog_1' : {'age' : 13, 'height' : 20}, 'dog_2' :  {'age' : 9, 'height' : 18}}

我想通过对外部 id 键进行分组(使用类似 key.split('_')[0] 的方法)找到每种动物的内部字典键的平均值.

最佳答案

您可以使用 itertools 模块中的 sum()groupby 执行类似的操作:

from itertools import groupby

a = {'cat_1' : {'age' : 5, 'height' : 15}, 'cat_2' :  {'age' : 1, 'height' : 7}, 'dog_1' : {'age' : 13, 'height' : 20}, 'dog_2' :  {'age' : 9, 'height' : 18}}

animals, final = {}, {}

for k,v in groupby(sorted(a.items(), key=lambda x:x[0].split('_')[0]), lambda x: x[0].split('_')[0]):
    animals[k] = [j for _, j in list(v)]


for k in animals:
    final[k] = {"height": sum(j["height"] for j in animals[k])/len(animals[k]),
    "age": sum(j["age"] for j in animals[k])/len(animals[k])}

print(final)

输出:

{'cat': {'height': 11.0, 'age': 3.0}, 'dog': {'height': 19.0, 'age': 11.0}}

关于python - 对外部键进行分组后求内部字典键的平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44282593/

相关文章:

python - 在多级字典中获取和设置值的最佳实践

Python:了解字典 View 对象

python - 从字典计算欧氏距离(sklearn)

python - urlretrieve 似乎损坏了图像文件

python - 从 DM.de 抓取客户评论

python - 如果任何列包含关键字之一,则删除行

C# 字典相当于 Python 的 get() 方法

python - 如何在Python中编辑以字典作为值的字典值?

python - 命令在终端或程序(Python 和 C++)中给出不同的行为

python - 将 read_sql 与 pyODBC 连接一起使用到 access 数据库是否安全?