Is it possible to add <key, value> pair at the end of the dictionary in python
A dict
in Python is not "ordered" - in Python 2.7+ there's collections.OrderedDict
, but apart from that - no... The key point of a dictionary in Python is efficient key->lookup value... The order you're seeing them in is completely arbitrary depending on the hash algorithm...
No. Check the OrderedDict from collections module.
UPDATE
As of 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 thus have no beginning or end. The display order is arbitrary.
If you need order, you can use a list
of tuple
s instead of a dict
:
In [1]: mylist = []
In [2]: mylist.append(('key', 'value'))
In [3]: mylist.insert(0, ('foo', 'bar'))
You'll be able to easily convert it into a dict
later:
In [4]: dict(mylist)
Out[4]: {'foo': 'bar', 'key': 'value'}
Alternatively, use a collections.OrderedDict
as suggested by IamAlexAlright.