Is it possible to add a pair of <key, value> to the end of a dictionary in python

When I introduce a new pair, it is inserted at the beginning of the dictionary. Can I add it at the end?

+8
source share
3 answers

UPDATE

Starting with Python 3.7, dictionaries remember the insertion order . By simply adding a new value, you can be sure that it will be β€œat the end” if you iterate over the dictionary.


Dictionaries have no order and, therefore, have no beginning or end. The display order is arbitrary. If you need order, you can use list tuple instead of dict :

 In [1]: mylist = [] In [2]: mylist.append(('key', 'value')) In [3]: mylist.insert(0, ('foo', 'bar')) 

You can easily convert it to a dict later:

 In [4]: dict(mylist) Out[4]: {'foo': 'bar', 'key': 'value'} 

Alternatively, use collections.OrderedDict as suggested by IamAlexAlright.

+13
source

Not. Check out the OrderedDict module from the collection.

+5
source

A dict in Python is not "ordered" - in Python 2.7+ there are collections.OrderedDict , but apart from that - no ... The key point of the dictionary in Python is the effective value of key-> lookup .. The order in which you see them is completely arbitrary depending on the hashing algorithm ...

+5
source

All Articles