简体   繁体   English

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

[英]Why does dict(enumerate(example)) return a randomized dictionary?

When I run this simple program: 当我运行这个简单的程序时:

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

each run results in a different (index, value) pair. 每次运行都会产生不同的(索引,值)对。 For example: 例如:

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

Why is that? 这是为什么?

from the docs https://docs.python.org/3/reference/datamodel.html#object. 来自docs 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. 注意默认情况下, strbytesdatetime对象的__hash__()值使用不可预测的随机值“加盐”。 Although they remain constant within an individual Python process, they are not predictable between repeated invocations of Python. 尽管它们在单个Python进程中保持不变,但是在重复调用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. 在版本3.3中更改:默认情况下启用哈希随机化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用枚举返回字典 - Using enumerate to return a dictionary 为什么dict与dict.keys()联合返回一个集合? - Why does dict unioned with dict.keys() return a set? 为什么将枚举 function 结果传递给 dict 构造函数会产生类型警告? - Why does passing an enumerate function result to the dict constructor yield a type warning? 为什么使用 enumerate() 循环遍历字典值元组会抛出错误? - Why does looping through dict-value tuples using `enumerate()` throw an error? 在迭代过程中修改列表和字典,为什么在dict上失败? - Modify list and dictionary during iteration, why does it fail on dict? For Loop Enumerate vs dict on enumerate - For Loop Enumerate vs dict on enumerate 为什么将Python dict转换为元组会返回一组键? - Why does casting a Python dict to a tuple return a tuple of keys? 为什么 Python 的 dict.keys() 返回一个列表而不是一个集合? - Why does Python's dict.keys() return a list and not a set? 当值为列表时,dict(sorted(dictionary.items(), key=operator.itemgetter(1)) 并不总是返回有序的dict - dict(sorted(dictionary.items(), key=operator.itemgetter(1)) does not always return a ordered dict when the value is a list 为什么dict(k = 4,z = 2).update(dict(l = 1))在Python中返回None? - Why does dict(k=4, z=2).update(dict(l=1)) return None in Python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM