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

1

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

0

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

5

No. Check the OrderedDict from collections module.

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' ) 

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} 

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy