我有这样的事情:
A = {"Green":{"Small": 5, "Medium": 10, "Large": 15}, "Yellow": {"Small": 7, "Medium": 14, "Large": 21}}
B = {"Green":{"Small": 1, "Medium": 2, "Large": 3}, "Yellow": {"Small": 3, "Medium": 6, "Large": 9}}
我想写一个函数来获取字典" C"像这样:
C = {"Green":{"Small": 6, "Medium": 12, "Large": 18}, "Yellow": {"Small": 10, "Medium": 20, "Large": 30}}
这只是它键的每个值的总和(在所有词典中都是相同的。现在我的"解决方案"太长了,当然也不优雅。任何人都可以给关于我如何能够实现相对较短的功能的一些指示?
答案 0 :(得分:2)
旧的循环:
C = {}
for k, v in A.items():
inner = {}
for inner_k, inner_v in v.items():
inner[inner_k] = inner_v + B[k][inner_k]
C[k] = inner
>>> C
{'Green': {'Large': 18, 'Medium': 12, 'Small': 6},
'Yellow': {'Large': 30, 'Medium': 20, 'Small': 10}}
答案 1 :(得分:1)
以OP形式接受任意数量字典的函数描述:
from pprint import pprint
def dsum(*args):
return {
k1: {
k: sum(d.get(k1, dict()).get(k, 0) for d in args)
for k in set.union(*(set(d.get(k1, dict())) for d in args))
}
for k1 in set.union(*(set(d) for d in args))
}
A = {"Green":{"Small": 5, "Medium": 10, "Large": 15}, "Yellow": {"Small": 7, "Medium": 14, "Large": 21}}
B = {"Green":{"Small": 1, "Medium": 2, "Large": 3}, "Yellow": {"Small": 3, "Medium": 6, "Large": 9}}
C = {"Green":{"Small": 6, "Medium": 12, "Large": 18}, "Yellow": {"Small": 10, "Medium": 20, "Large": 30}}
testC = dsum(A, B)
assert C == testC
pprint(testC)
答案 2 :(得分:0)
C={k: {kk: v + B[k][kk] for kk, v in a.items()} for k, a in A.items()}
更喜欢python2中的.iteritems()
答案 3 :(得分:0)
缺少密钥的解决方案:
def merge_by_addition(d1, d2):
def m2(d1_, d2_):
keys_ = set(d1_.keys()) | set(d2_.keys())
return {k_: (d1_.get(k_, 0) + d2_.get(k_, 0)) for k_ in keys_}
keys = set(d1.keys()) | set(d2.keys())
return {k: m2(d1.get(k, {}), d2.get(k, {})) for k in keys}