Categories
Python Answers

How to keep dictionary keys/values in same order as declared with Python?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *