为什么dict(enumerate(example))返回随机字典?

2024-09-20 03:33:42 发布

您现在位置:Python中文网/ 问答频道 /正文

当我运行这个简单的程序时:

example: {'left', 'right', 'up', 'down'}
new_dict = dict(enumerate(example))
print(new_dict)

每次运行都会产生不同的(索引、值)对。例如:

MacBook-Air:Desktop mymac$ python3 example.py
{0: 'right', 1: 'down', 2: 'left', 3: 'up'}
MacBook-Air:Desktop mymac$ python3 example.py
{0: 'left', 1: 'up', 2: 'down', 3: 'right'}
MacBook-Air:Desktop mymac$ python3 example.py
{0: 'down', 1: 'left', 2: 'right', 3: 'up'}

为什么?你知道吗


Tags: py程序rightnewexampleairleftdict
1条回答
网友
1楼 · 发布于 2024-09-20 03:33:42

从文档https://docs.python.org/3/reference/datamodel.html#object.hash

Note By default, the __hash__() values of str, bytes and datetime objects are “salted” with an unpredictable random value. Although they remain constant within an individual Python process, they are not predictable between repeated invocations of Python.

Changing hash values affects the iteration order of dicts, sets and other mappings.

Changed in version 3.3: Hash randomization is enabled by default.

相关问题 更多 >