为什么这种通过字典中的值获取键的方法有效?

2024-06-02 06:29:44 发布

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

从这个来源: https://www.geeksforgeeks.org/python-get-key-from-value-in-dictionary/

我想知道为什么会这样

# creating a new dictionary 
my_dict ={"java":100, "python":112, "c":11} 

# list out keys and values separately 
key_list = list(my_dict.keys()) 
val_list = list(my_dict.values()) 

print(key_list[val_list.index(100)]) 
print(key_list[val_list.index(112)]) 

我理解代码,但我认为字典没有存储任何内部顺序,那么.keys()和.values()方法如何/为什么保持顺序

这里是python新手

谢谢


Tags: keyhttpsindexdictionary顺序mywww来源
1条回答
网友
1楼 · 发布于 2024-06-02 06:29:44

自从Python 3.6以来dict在实现新的紧凑字典类型后保持了顺序

What's New in Python 3.6 New dict implementation

The dict type now uses a “compact” representation based on a proposal by Raymond Hettinger which was first implemented by PyPy. The memory usage of the new dict() is between 20% and 25% smaller compared to Python 3.5.

The order-preserving aspect of this new implementation is considered an implementation detail and should not be relied upon (this may change in the future, but it is desired to have this new dict implementation in the language for a few releases before changing the language spec to mandate order-preserving semantics for all current and future Python implementations; this also helps preserve backwards-compatibility with older versions of the language where random iteration order is still in effect, e.g. Python 3.5).

从Python3.7开始上述内容不再是实现细节,而dict维护秩序成为官方语言细节

[Python-Dev] Guarantee ordered dict literals in v3.7?

Make it so. "Dict keeps insertion order" is the ruling. Thanks!

相关问题 更多 >