Dictionary Operations in Python

1. Dictionary Comparison

The comparision sequence for dictionaries is as folows:

  1. First, compare the number of elements in the dictionary; the one with more elements is considered larger;
  2. Compare the keys of the dictionary. When comparing keys, note that the order is based on the return value of keys;
  3. Compare the values of the dictionary. Values are compared based on the return value of items, primarily by numerical and alphabetical order;
  4. If all previous comparisons are equal, then the dictionaries are considered equal.

cmp(dict1, dict2): returns 0 if both dictionaries have the same elements, 1 if dict1 is greater than dict2, and -1 if dict1 is less thann dict2.

>>> dict1={'name':'af','better':'yes'}
>>> dict2={'age':'12'}
>>> cmp(dict1,dict2)
1
>>> dict1={'name':'kel'}
>>> dict2={}
>>> cmp(dict1,dict2) # dict1 has more elements than dict2
1
>>> dict3={'name':'a'}
>>> cmp(dict1,dict3) # 'kel' is larger than 'a' because 'k' comes after 'a'
1
>>> dict4={'name':'kel','age':27}
>>> dict5={'name':'mel','age':17} # when comparing, it uses the order of keys, so 27 is larger than 17, not based on the visible order
>>> cmp(dict4,dict5)
1
# the keys order is 'age', 'name'

2. Dictionary Merging

  1. Using the method dict(d1.items() + d2.items())
>>> d1={'a':'1','b':'2'}
>>> d2={'c':'3'}
>>> dict(d1.items()+d2.items())
{'a': '1', 'c': '3', 'b': '2'}
>>> 
>>> dict(d2.items()+d1.items())
{'a': '1', 'c': '3', 'b': '2'}
>>> 
>>> # if there are identical keys, they will be merged
>>> d3={'c':'3','b':'4'}
>>> dict(d3.items()+d1.items())
{'a': '1', 'c': '3', 'b': '2'}
>>> dict(d1.items()+d3.items())
{'a': '1', 'c': '3', 'b': '4'}

Note:

  • d1.items() retrieves a list of key-value pairs from the dictionary.
  • d1.items() + d2.items() creates a new list.
  • dict(d1.items()+d2.items()) converts the combined list into a new dictionary.
  1. Using the update() method of the dictionary
>>> d1 
{'a': '1', 'b': '2'}
>>> d3
{'c': '3', 'b': '4'}
>>> d4={}
>>> d4.update(d1)
>>> d4
{'a': '1', 'b': '2'}
>>> d4.update(d3)
>>> d4
{'a': '1', 'c': '3', 'b': '4'}
>>> # using copy
>>> d4=d1.copy()
>>> d4
{'a': '1', 'b': '2'}
>>> d4.update(d3)
>>> d4
{'a': '1', 'c': '3', 'b': '4'}
  1. Using the dict(d1, **d2) method
>>> d1 
{'a': '1', 'b': '2'}
>>> d3
{'c': '3', 'b': '4'}
>>> 
>>> dict(d1,**d3)
{'a': '1', 'c': '3', 'b': '4'}
>>> dict(d3,**d1)
{'a': '1', 'c': '3', 'b': '2'}
  1. Using a standard for loop to handle dictionaries
>>> d1
{'a': '1', 'b': '2'}
>>> d3
{'c': '3', 'b': '4'}
>>> d4={}
>>> 
>>> for i,v in d1.items():
...     d4[i]=v
... 
>>> d4
{'a': '1', 'b': '2'}
>>> for i,v in d3.items():
...     d4[i]=v
... 
>>> d4
{'a': '1', 'c': '3', 'b': '4'}

Tags: python Dictionary comparison merge operations

Posted on Tue, 08 Sep 2026 16:16:44 +0000 by anser316