取嵌套字典嵌套值的总和 [英] Taking sums of nested values of nested dictionary

查看:333
本文介绍了取嵌套字典嵌套值的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个嵌套字典

 dict_features =  {'agitacia/6.txt': {'samoprezentacia': 0, 'oskorblenie': 1},
                   'agitacia/21.txt': {'samoprezentacia': 0, 'oskorblenie': 0}}

我正在尝试输出一个新的字典 features_agit_sum ,它由前一个字典中的一个键组成,一个更深字典。所以我需要总和0 + 1这是int类型。输出应该是:

I'm trying to output a new dictionary features_agit_sum which consists of a key from a previous dictionary and a sum of values of a "deeper" dictionary. So I need to sum 0+1 that is int type. The output should be:

{'agitacia/6.txt': 1, 'agitacia/21.txt': 0}

以下是不同错误的几次尝试;不要如何正确迭代:

Below are several attempts with different errors; don't how to iterate correctly:

features_agit_sum = {}
def vector_agit_sum(dict_features):
    for key, value in dict_features:
        features_agit_sum[key] = sum(dict_features.items()[key])
        print (features_agit_sum)
    return features_agit_sum




ValueError:要解压缩的值太多(预期2)
dict_features.items()[key] - 尝试访问更深层次的

ValueError: too many values to unpack (expected 2) dict_features.items()[key] - try to access deeper dict



features_agit_sum = {}
def vector_agit_sum(dict_features):
    for key in dict_features:
        for item, value in dict_features.items():
            features_agit_sum[key] = sum([item])
            print (features_agit_sum)
    return features_agit_sum




TypeError:不支持的操作数类型+:'int'和'str' - 为什么
是整数!

TypeError: unsupported operand type(s) for +: 'int' and 'str' - Why, it's integers!



features_agit_sum = {}
def vector_agit_sum(dict_features):
    files = dict_features.keys()
    for key, value in dict_features.items():
        features_agit_sum[files] = sum(dict_features.items()[key])
        print (features_agit_sum)
    return features_agit_sum




TypeError:'dict_items'对象不可下标

TypeError: 'dict_items' object is not subscriptable


推荐答案

使用字母理解:

{key: sum(value.itervalues()) for key, value in dict_features.iteritems()}

如果你使用Python 3,删除 iter 前缀,所以使用 .values() .items()

If you are using Python 3, remove the iter prefixes, so use .values() and .items().

演示:

>>> dict_features =  {'agitacia/6.txt': {'samoprezentacia': 0, 'oskorblenie': 1}, 'agitacia/21.txt': {'samoprezentacia': 0, 'oskorblenie': 0}}
>>> {key: sum(value.itervalues()) for key, value in dict_features.iteritems()}
{'agitacia/21.txt': 0, 'agitacia/6.txt': 1}

这篇关于取嵌套字典嵌套值的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆