When I introduce new pair it is inserted at the beginning of dictionary. Is it possible to append it at the end?
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.
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.
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