比较两个字典的键,并创建一个包含键,值对与另一个词典中的键不匹配的字典-Python

时间:2019-04-05 02:19:45

标签: python-3.x

我想比较dict_1dict_2之间的键,并创建一个new_dict,其中只包含不匹配的键及其对应的值。我有两个像这样的字典:

dict_1 = {'a':'1', 'b':'1', 'c': None}
dict_2 = {'d': '1', 'a': '2'}

我希望输出类似于:aa匹配,所以我希望将其排除在new_dict中。

new_dict = {'b':'1', 'c': None, 'd': '1'}

我尝试过:

new_dict = {}
for key in dict_1.items():
for key2 in dict_2.items():
    if key == key2:

但是我不确定如何从这里开始,或者这不是正确的方法。请帮忙!

2 个答案:

答案 0 :(得分:2)

您可以对dict.keys的结果执行类似集合的操作:

对于类似集合的视图,为抽象基类collections.abc.Set定义的所有操作都是可用的(例如==<^)。

所以您可以做类似的事情

dict_1 = {'a':'1', 'b':'1', 'c': None}
dict_2 = {'d': '1', 'a': '2'}

keys = dict_1.keys() ^ dict_2.keys()

new_dict = {k: dict_1.get(k, dict_2.get(k)) for k in keys}

答案 1 :(得分:0)

您需要获取每个词典的键,并找到唯一的键。我按集来做。看看:

# your dictionaries
dict_1 = {'a':'1', 'b':'1', 'c': None}
dict_2 = {'d': '1', 'a': '2'}

# find their keys
dict_1_keys = set(dict_1.keys())
dict_2_keys = set(dict_2.keys())
# find unique keys
unique_keys = (dict_1_keys.union(dict_2_keys)) - (dict_1_keys.intersection(dict_2_keys))

dict_results = {}

for key in unique_keys:
    if dict_1.get(key) is not None:
        dict_results[key] = dict_1.get(key)
    else:
        dict_results[key] = dict_2.get(key)

print(dict_results)