Is it possible to retrieve items from a Python dictionary in the order that they were inserted?
You can use the get() method of the dictionary ( dict ) to get any default value without an error if the key does not exist. Specify the key as the first argument. The corresponding value is returned if the key exists, and None is returned if the key does not exist.
OrderedDict preserves the order in which the keys are inserted. A regular dict doesn't track the insertion order and iterating it gives the values in an arbitrary order. By contrast, the order the items are inserted is remembered by OrderedDict.
The standard Python dict
does this by default if you're using CPython 3.6+ (or Python 3.7+ for any other implementation of Python).
On older versions of Python you can use collections.OrderedDict
.
Use OrderedDict(), available since version 2.7
Just a matter of curiosity:
from collections import OrderedDict a = {} b = OrderedDict() c = OrderedDict() a['key1'] = 'value1' a['key2'] = 'value2' b['key1'] = 'value1' b['key2'] = 'value2' c['key2'] = 'value2' c['key1'] = 'value1' print a == b # True print a == c # True print b == c # False
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With