python - 在 Python 中迭代时如何在字典中选择键

标签 python dictionary

my_dict = {'a':10, 'b':20, 'c':30}

for key in my_dict:
    print key, my_dict[key]

给予

a 10
c 30
b 20

my_dict = {'a':10, 'c':30, 'b':20}

for key in my_dict:
    print key, my_dict[key]

结果相同

a 10
c 30
b 20

我想知道为什么输出不像 a 10 b 20 c 30。在遍历字典时如何选择键?是随机的吗?

最佳答案

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.

dict() 中键的顺序未定义(这取决于您使用的是哪种 Python 实现)。为了以有序的方式遍历字典:

my_dict = {'a': 10, 'b': 20, 'c': 30}
for key in sorted(my_dict.keys()):
    print key, my_dict[key]

这将为您提供正确的顺序:

a 10
b 20
c 30

键没有排序的原因是 dict() 使用哈希表来存储它们,这也是为什么你只能有一个唯一的键以及为什么你可以有组合键的原因可散列的对象。键按它们的哈希值排序,更深入的解释见 this SO question

关于python - 在 Python 中迭代时如何在字典中选择键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34306021/

相关文章:

python - 如何在调用函数后存储输出并在下次运行中使用它

python - 神秘时间转换( Pandas 和日期时间)

python在html中显示unicode

python - 在 django 中重新启动 postgres 连接

python - 如何制作一个以值作为元组的字典?

python - 合并甚至有一个共同元素的集合

python - 将字典值转换为不同的列表 - 字典值是元组 - Python

list - 从 map 列表中解析 Gson。如何?

ios - "Preloading"Swift 中带键的字典

python - 具有来自单个列表的嵌套类别的字典