[英]Add values of two dictionaries with the same keys but variable lists of tuples of values
我有两个字典 (dict1, dict2) 有 100 个相同的键但不同的元组列表作为值:
dict1 = {'M1': [(50, 'M'), (4, 'K')], 'N2': [(500, 'N'), (3, 'C'), (7, ' K')], 'S3': ...}
dict2 = {'M1': [(46, 'M'), (2, 'K'), (11, 'F')], 'N2': [(400, 'N'), (5, ' C')], 'S3': ...}
我想创建一个新字典 (dict3),如果它们在元组的第一个位置具有相同的字母,则在其中添加值,如果不是,则必须将元组添加到新字典的值中:
dict3 = {'M1': [(96, 'M'), (6, 'K'), (11, 'F')], 'N2': [(900, 'N'), (8, ' C'), (7, 'K)], 'S3': ...}
我在用 python3 考虑这样的事情(这段代码不起作用):
dict1 = {'M1': [(50, 'M'), (4, 'K')], 'N2': [(500, 'N'), (3, 'C'), (7, 'K')]}
dict2 = {'M1': [(46, 'M'), (2, 'K'), (11, 'F')], 'N2': [(400, 'N'), (5, 'C')]}
dict3 = {}
for (val1, key1), (val2, key2) in zip(dict1, dict2):
if t1[1]==t2[1] for (t1, t2) in (key1, key2):
t3_0 = t1[0] + t2[0]
t3_1 = t1[1]
elif t1[1] not in t2[1]:
t3_0 = t1[0]
t3_1 = t1[1]
elif t2[1] not in t1[1]
t3_0 = t2[0]
t3_1 = t2[1]
key3 = [(t3_0, t3_1)]
# here val1=val2
dict3[val1] = key3
我非常感谢您的帮助。 谢谢你。
可能有几种方法可以做到这一点。 一个相对简单的方法是从元组的内部列表中构造字典——由于键值对是倒退的,这使得稍微复杂一些。
这是一种方法:
from collections import defaultdict
# Here is your test data
dict1 = {'M1': [(50, 'M'), (4, 'K')], 'N2': [(500, 'N'), (3, 'C'), (7, 'K')]}
dict2 = {'M1': [(46, 'M'), (2, 'K'), (11, 'F')], 'N2': [(400, 'N'), (5, 'C')]
# This dictionary will be you output
dict3 = defaultdict(list)
def generate_inner_dict(lst):
"""This helper takes a list of tuples and returns them as a dict"""
# I used a defaultdict again here because your example doesn't always have
# the same letters in each list of tuples. This will default to zero!
inner_dict = defaultdict(int)
for num, key in lst:
inner_dict[key] = num # Note that the key and value are flipped
return inner_dict
# loop over the keys in one dictionary - i'm assuming the outer keys are the same
for key in dict1:
# use the helper to get two dicts
vals1 = generate_inner_dict(dict1[key])
vals2 = generate_inner_dict(dict2[key])
# loop over the keys...
for inner_key in vals1:
value = vals1[inner_key] + vals2[inner_key] # add them together...
dict3[key].append((inner_key, value)) # and put them in the dictionary
# I turned the defaultdict back into a dict so it looks more obviously like your example
print(dict(dict3))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.