Reputation:
I have a python dictionary (say dict) in which I keep modifying values (the keys remain unaltered). Will the order of keys in the list given by dict.keys() change when I modify the values corresponding to the keys?
Upvotes: 4
Views: 1316
Reputation: 7177
Python dictionaries' key ordering should not be assumed constant.
However, there are other datastructures that do give consistent key ordering, that work a lot like dictionaries:
http://stromberg.dnsalias.org/~strombrg/treap/
http://stromberg.dnsalias.org/~strombrg/red-black-tree-mod/
BTW, you should not name a variable "dict", because there is a builtin type called "dict" that will be made invisible.
Upvotes: 0
Reputation: 172239
No, the order of the dict will not change because you change the values. The order depends on the keys only (or their hash value, to be more specific at least in CPython). However, it may change between versions and implementations of Python, and in Python 3.3, it will change every time you start Python.
Upvotes: 1
Reputation: 10489
No, a python dictionary has an ordering for the keys but does not guarantee what that order will be or how it is calculated.
Which is why they are not guaranteed to be ordered in the first place.
The values stored in the dictionary do not have an effect on the hash values of the keys and so will not change ordering.
Taken from the Python Documentation:
The keys() method of a dictionary object returns a list of all the keys used in the dictionary, in arbitrary order (if you want it sorted, just apply the sorted() function to it). To check whether a single key is in the dictionary, use the in keyword.
Upvotes: 2