When I introduce new pair it is inserted at the beginning of dictionary. Is it possible to append it at the end?
问题:
回答1:
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.
回答2:
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...
回答3:
No. Check the OrderedDict from collections module.
回答4:
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' )