Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you retrieve items from a dictionary in the order that they're inserted?

Is it possible to retrieve items from a Python dictionary in the order that they were inserted?

like image 234
readonly Avatar asked Sep 13 '08 20:09

readonly


People also ask

How do I retrieve something from the dictionary?

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.

Does dictionary preserve insertion order?

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.


2 Answers

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.

like image 178
dF. Avatar answered Oct 14 '22 23:10

dF.


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 
like image 20
rewgoes Avatar answered Oct 14 '22 22:10

rewgoes