Categories
Python Answers

How to implement an ordered, default dict with Python?

Spread the love

Sometimes, we want to implement an ordered, default dict with Python.

In this article, we’ll look at how to implement an ordered, default dict with Python.

How to implement an ordered, default dict with Python?

To implement an ordered, default dict with Python, we can use the OrderedDict.fromkeys method.

For instance, we write

from collections import OrderedDict

keys = ['a', 'b', 'c']
od = OrderedDict.fromkeys(keys)

to call OrderedDict.fromkeys with the keys list to returned an ordered dict with the keys being the values in the keys list.

And the values are all set to None.

Conclusion

To implement an ordered, default dict with Python, we can use the OrderedDict.fromkeys method.

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 *