Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 353
user1801180 Avatar asked Nov 05 '12 19:11

user1801180


3 Answers

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

like image 160
Lev Levitsky Avatar answered Nov 15 '22 13:11

Lev Levitsky


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

like image 35
Jon Clements Avatar answered Nov 15 '22 14:11

Jon Clements


No. Check the OrderedDict from collections module.

like image 20
alexvassel Avatar answered Nov 15 '22 14:11

alexvassel