Typefully

Python Dictionaries: Does Order Matter?

Avatar

Share

 • 

3 years ago

 • 

View on X

Let's travel back in time to a pre-Python 3.6 era The order of items was meaningless After all, what matters is the key-value association But things changed in Python 3.6, and again in 3.7, and now the order is maintained But beware, they're still mappings not sequences
The change in Python 3.6 wasn't specifically designed to make dictionaries ordered, it was a by-product of other updates to the internal workings of dictionaries Python 3.7 formalised this, so you can now rely on dictionaries being ordered
But as you can see from the code in the first tweet, this has a different meaning to the order in a sequence, say
In a sequence, such as a list, two lists with the same values but different order are _not_ equal >>> first_list = [2, 4, 6] >>> second_list = [2, 6, 4] >>> first_list == second_list False
But, two dictionaries with the same items in different orders are equal… >>> first_dict = {"two": 2, "four": 4, "six": 6} >>> second_dict = {"two": 2, "six": 6, "four": 4} >>> first_dict == second_dict True
I've written in more detail about mappings in this article, which is part of a longer series on data structure categories Follow the link in the image, and you can subscribe to receive new articles in your inbox Or just look for The Python Coding Stack in that other place…
Avatar

Stephen Gruppetta

@s_gruppetta_ct

Constantly looking for innovative ways to talk and write about Python • Mentoring learners • Writing about Python • Writing about technical writing