Related Articles

Related Articles

Python | Difference in keys of two dictionaries
  • Last Updated : 12 Feb, 2019

Given two dictionaries dic1 and dic2 which may contain same-keys, find the difference of keys in given dictionaries.

Code #1 : Using set to find keys that are missing.

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

{'key2:'}

 
Code #2 : Finding keys in dict2 which are not in dict1.

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:



key4
key3

 
Code #3: Finding keys in dict1 which are not in dict2.

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

key12

 
Code #4 : Finding the same keys in two dictionaries.

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

{'key2', 'key1'}

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.




My Personal Notes arrow_drop_up
Recommended Articles
Page :