如何求和dict中的dict元素



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

list = [{a: {b:1, c:2}}, {d: {b:3, c:4}}, {a: {b:2, c:3}}]

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

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

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

代码:

lst = [{'a': {'b':1, 'c':2}}, {'d': {'b':3, 'c':4}}, {'a': {'b':2, 'c':3}}]
p={}
for l in lst:
for key , val in l.items():
if key in p and val != p[key]:
p.update({key:{k: p[key].get(k, 0) + val.get(k, 0) for k in set(p[key])}})
else:
p.update(l)

输出:

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

通过使用defaultdict,我们可以稍微简化逻辑:

# Using default dict
from collections import defaultdict
original_list = [{'a': {'b':1, 'c':2}}, {'d': {'b':3, 'c':4}}, {'a': {'b':2, 'c':3}}]
out = defaultdict(lambda: defaultdict(int))
for outter_dict in original_list:
for outter_key, inner_dict in outter_dict.items():
for inner_key, inner_value in inner_dict.items():
out[outter_key][inner_key] += inner_value
print(out)
out_list = [{key: dict(value) for key, value in out.items()}]
print(out_li)

输出:

defaultdict(<function <lambda> at 0x103c18a60>, {'a': defaultdict(<class 'int'>, {'b': 3, 'c': 5}), 'd': defaultdict(<class 'int'>, {'b': 3, 'c': 4})})
[{'a': {'b': 3, 'c': 5}, 'd': {'b': 3, 'c': 4}}]

备注

  • out是嵌套的defaultdict,其值是defaultdict,其值为整数
  • 在3个嵌套循环之后,我们将defaultdictout转换为字典列表,以符合输出要求

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

  • 首先,我为进行了一个循环,以获得所有的主键和副键:

# 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}}
  • 稍后,我对每个字典项进行了循环,并在最终dict中添加了相应的键

# 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}}

最新更新