Does the order of keys in .keys () dictionaries change in python dictionary if values ​​are changed?

I have a python dictionary (say dict) in which I keep changing values ​​(keys remain unchanged). Will the order of the keys in the list set by dict.keys () change when I change the values ​​corresponding to the keys?

+4
source share
3 answers

No, the python dictionary has an order for the keys, but does not guarantee that this order will be or how it is calculated.
That is why they are not guaranteed that they are ordered in the first place.
The values ​​stored in the dictionary do not affect the hash values ​​of the keys and therefore will not change the order.

Adapted from the Python Documentation :

The keys () method of a dictionary object returns a list of all the keys used in the dictionary in random order (if you want it to be sorted, just apply the sorted () function to it). To check if one key is in the dictionary, use the keyword.

+2
source

No, the order of the dict will not change, because you change the values. The order depends only on the keys (or their hash values, more specifically, at least in CPython). However, it can change between versions and implementations of Python, and in Python 3.3 it will change every time you start Python.

+1
source

The order of keys in Python dictionaries cannot be considered constant.

However, there are other data structures that give a consistent key order, which are very similar to dictionaries:

http://stromberg.dnsalias.org/~strombrg/treap/

http://stromberg.dnsalias.org/~strombrg/red-black-tree-mod/

By the way, you should not name the variable "dict" because there is a built-in type called "dict" that will be invisible.

0
source

Source: https://habr.com/ru/post/1484322/


All Articles