给定两个字典,我想看看它们的交集和差异,并对与唯一元素相交并执行g的元素执行f函数,这就是我找出d1和d2是两个字典的唯一和相交元素的方法,如何将d_intersection和d_difference作为字典打印在元组中?输出应该看起来像这样({相交的键,值},{差异的键,值}),例如:
d1 = {1:30, 2:20, 3:30, 5:80} d2 = {1:40, 2:50, 3:60, 4:70, 6:90}
输出应为 ({1: 70, 2: 70, 3: 90}, {4: 70, 5: 80, 6: 90})
({1: 70, 2: 70, 3: 90}, {4: 70, 5: 80, 6: 90})
dic = {} d_intersect = set(d1) & set(d2) d_difference = set(d1) ^ set(d2) for i in d_intersect: dic.update({i : f(d1[i],d2[i])}) for j in d_difference: dic.update({j : g(d1[j],d2[j])})
有人可以告诉我我哪里出了问题,为什么我的代码给出了关键错误4?
尽管可能存在更有效的方法,但这是一种方法。
d1 = {1:30, 2:20, 3:30, 5:80} d2 = {1:40, 2:50, 3:60, 4:70, 6:90} d_intersect = {} # Keys that appear in both dictionaries. d_difference = {} # Unique keys that appear in only one dictionary. # Get all keys from both dictionaries. # Convert it into a set so that we don't loop through duplicate keys. all_keys = set(d1.keys() + d2.keys()) # Python2.7 #all_keys = set(list(d1.keys()) + list(d2.keys())) # Python3.3 for key in all_keys: if key in d1 and key in d2: # If the key appears in both dictionaries, add both values # together and place it in intersect. d_intersect[key] = d1[key] + d2[key] else: # Otherwise find out the dictionary it comes from and place # it in difference. if key in d1: d_difference[key] = d1[key] else: d_difference[key] = d2[key]
输出: {1:70,2:70,3:90} {4:70,5:80,6:90}
输出:
{1:70,2:70,3:90}
{4:70,5:80,6:90}