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/