📜  Python|两个字典的键的差异

📅  最后修改于: 2022-05-13 01:54:19.617000             🧑  作者: Mango

Python|两个字典的键的差异

给定两个可能包含相同键的字典dic1dic2 ,找出给定字典中键的差异。

代码 #1:使用 set 查找丢失的键。

# Python code to find the difference in
# keys in two dictionary
  
# Initialising dictionary 
dict1= {'key1':'Geeks', 'key2':'For', 'key3':'geeks'}
dict2= {'key1':'Geeks', 'key2:':'Portal'}
  
diff = set(dict2) - set(dict1)
  
# Printing difference in
# keys in two dictionary
print(diff)
输出:
{'key2:'}


代码 #2:在 dict2 中查找不在dict1 中的键。

# Python code to find difference in keys in two dictionary
  
# Initialising dictionary 
dict1= {'key1':'Geeks', 'key2':'For'}
dict2= {'key1':'Geeks', 'key2':'For', 'key3':'geeks',
        'key4': {'GeekKey1': 12, 'GeekKey2': 22, 'GeekKey3': 32 }}
  
for key in dict2.keys():
    if not key in dict1:
  
        # Printing difference in
        # keys in two dictionary
        print(key)
输出:
key4
key3


代码 #3:在 dict1 中查找不在dict2 中的键。

# Python code to find difference in keys in two dictionary
  
# Initialising dictionary 
dict1= {'key1':'Geeks', 'key12':'For'}
dict2= {'key1':'Geeks', 'key2':'For', 'key3':'geeks',
        'key4': {'GeekKey1': 12, 'GeekKey2': 22, 'GeekKey3': 32 }}
          
for key in dict1.keys():
    if not key in dict2:
  
        # Printing difference in
        # keys in two dictionary
        print(key)
输出:
key12


代码 #4:在两个字典中查找相同的键。

# Python code to find difference in keys in two dictionary
  
# Initialising dictionary 
dict1= {'key1':'Geeks', 'key2':'For'}
dict2= {'key1':'Geeks', 'key2':'For', 'key3':'geeks',
        'key4': {'GeekKey1': 12, 'GeekKey2': 22, 'GeekKey3': 32 }}
          
print(set(dict1.keys()).intersection(dict2.keys()))
输出:
{'key2', 'key1'}