繁体   English   中英

如何对dicts中的dict元素求和

[英]How to sum dict elements inside dicts

在 Python 我有一个包含字典的字典列表。

列表 = [{a: {b:1, c:2}}, {d: {b:3, c:4}}, {a: {b:2, Z4A8A08F09D347B737955368]

我想要一个包含字典的最终列表,其中包含的字典将包含所有具有相同字典作为键的字典的总和。 即结果将是:

结果 = [{a: {b:3, c:5}}, {d: {b:3, c:4}}]

注意:列表中的每个 dict 都将包含相同数量的键、值对。

我不知道这是否是最好的方法,但它是这样的:

  • 首先,我创建了一个循环来获取所有主键和辅助键:

    # list containing the data
    lista = [{'a': {'b':1, 'c':2}}, {'d': {'b':3, 'c':4}}, {'a': {'b':2, 'c':3}}]
    
    # empty list with keys
    primary_keys = []
    secondary_keys = []
    
    # for each dict in the list it appends the primary key and the secondary key
    for dic in lista:
        for key in dic.keys():
            primary_keys.append(key)
            for key2 in dic[key].keys():
                secondary_keys.append(key2)
    
    # prints all the keys
    print('Primary keys:',primary_keys)
    print('Secondary keys:',secondary_keys)

结果:

Primary keys: ['a', 'd', 'a']

Secondary keys: ['b', 'c', 'b', 'c', 'b', 'c']
  • 然后我用所有的组合做了一个最终的字典:

    # creates the final dict from the list
    dict_final = dict.fromkeys(primary_keys)
    
    # for all primary keys creates a secondary key
    for pkey in dict_final.keys():
        dict_final[pkey] = dict.fromkeys(secondary_keys)
        # for all secondary keys puts a zero
        for skey in dict_final[pkey].keys():
            dict_final[pkey][skey] = 0
    
    # prints the dict
    print(dict_final)

结果:

{'a': {'b': 0, 'c': 0}, 'd': {'b': 0, 'c': 0}}
  • 后来我对每个字典项进行了循环,并添加到最终字典中的相应键中

    # for each primary and secondary keys in the dic list sums into the final dict
    for dic in lista:
        for pkey in dict_final.keys():
            for skey in dict_final[pkey].keys():
                try:
                    dict_final[pkey][skey] += dic[pkey][skey]
                except:
                    pass
    
    # prints the final dict
    print(dict_final)

结果:

{'a': {'b': 3, 'c': 5}, 'd': {'b': 3, 'c': 4}}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM