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

When I introduce new pair it is inserted at the beginning of dictionary. Is it possible to append it at the end?



Solution 1:[1]

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...

Solution 2:[2]

No. Check the OrderedDict from collections module.

Solution 3:[3]

dictionary data is inorder collection if u add data to dict use this : Adding a new key value pair

Dic.update( {'key' : 'value' } )

If key is string you can directly add without curly braces

Dic.update( key= 'value' )

Solution 4:[4]

If you intend for updated values to move to the end of the dict then you can pop the key first then update the dict.

For example:

In [1]: number_dict = {str(index): index for index in range(10)}
In [2]: number_dict.update({"3": 13})
In [3]: number_dict
Out[3]: 
{'0': 0,
 '1': 1,
 '2': 2,
 '3': 13,
 '4': 4,
 '5': 5,
 '6': 6,
 '7': 7,
 '8': 8,
 '9': 9}

In [4]: number_dict = {str(index): index for index in range(10)}
In [5]: number_dict.pop("3", None)
In [6]: number_dict.update({"3": 13})
In [7]: number_dict
Out[7]: 
{'0': 0,
 '1': 1,
 '2': 2,
 '4': 4,
 '5': 5,
 '6': 6,
 '7': 7,
 '8': 8,
 '9': 9,
 '3': 13}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jon Clements
Solution 2 alexvassel
Solution 3 mamal
Solution 4