Sometimes, we want to keep dictionary keys/values in same order as declared with Python.
In this article, we’ll look at how to keep dictionary keys/values in same order as declared with Python.
How to keep dictionary keys/values in same order as declared with Python?
To keep dictionary keys/values in same order as declared with Python, we can use the OrderDict
class to create our dictionary.
For instance, we write:
from collections import OrderedDict
d = {'ac': 33, 'gw': 20, 'ap': 102, 'za': 321, 'bs': 10}
ordered_d = OrderedDict(d)
print(ordered_d)
We import the OrderedDict
class from the collections
module.
Then we declared a regular dictionary and assigned it to d
.
Next, we use d
as the argument of OrderedDict
and assigned it to ordered_d
.
Therefore, ordered_d
is:
OrderedDict([('ac', 33), ('gw', 20), ('ap', 102), ('za', 321), ('bs', 10)])
Conclusion
To keep dictionary keys/values in same order as declared with Python, we can use the OrderDict
class to create our dictionary.