简体   繁体   中英

Compare the keys of two dictionaries and create a dictionary with key, value pairs that does not match the key in the other dictionary - Python

I want to compare the keys between dict_1 and dict_2 and create a new_dict that contains only the non-matched keys and their corresponding values. I have two dicts like this:

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

I want the output to be like: a and a matches so I want it to be excluded in the new_dict .

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

I tried this:

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

But I'm not sure how to proceed from here or maybe this is not the right way to do it. Please Help!

You can perform set-like operations on the result of dict.keys :

For set-like views, all of the operations defined for the abstract base class collections.abc.Set are available (for example, == , < , or ^ ).

So you can do something like

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}

You'd need to get the keys of each dictionary, and find the unique ones. I did it as sets. Take a look:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM