Python - Python 2.X and 3.X dictionary comparisons

Introduction

In Python 2.X, dictionaries support magnitude comparisons, as though you were comparing sorted key/value lists:

c:\python27\python 
D1 = {'a':1, 'b':2} 
D2 = {'a':1, 'b':3} 
D1 == D2                            # Dictionary equality: 2.X + 3.X 
#False 
D1 < D2                             # Dictionary magnitude: 2.X only 
#True 

Magnitude comparisons for dictionaries are removed in Python 3.X.

c:\python33\python 
D1 = {'a':1, 'b':2} 
D2 = {'a':1, 'b':3} 
D1 == D2 
#False 
D1 < D2 
#TypeError: unorderable types: dict() < dict() 

In Python 3.X you can either write loops to compare values by key, or compare the sorted key/value lists manually.

Demo

D1 = {'a':1, 'b':2} 
D2 = {'a':1, 'b':3} 

print( list(D1.items()) )
print( sorted(D1.items()) )
print( sorted(D1.items()) < sorted(D2.items()) )          # Magnitude test in 3.X 
print( sorted(D1.items()) > sorted(D2.items()) )

Result

Related Topic