我想打印出那本未分类的字典,但它是按顺序排列的。
这是我使用的代码(2.7.5Linux版本):
# id and name array are not the actual input. It is just a sample input. (So no hard-coding please)
# More importantly, I just want to figure out how to have the unsorted dictionary.
id = [1 ,4, 2]
name = ["John" , "Mary", "Alice"]
my_dict = {}
for x in range(len(id)):
my_dict[id[x]] = name[x]
for key, val in my_dict.items():
print(key, val)预期输出:
(1, "John")
(4, "Mary")
(2, "Alice")实际输出:
(1, "John")
(2, "Alice")
(4, "Mary")发布于 2019-08-23 06:54:45
它是而不是排序的。在Python2.7(和3.7发行版前)中,字典是无序的;这意味着它们可以按任何顺序存储。在你的测试中,巧合的是,它们是以这样的方式储存的。如果使用Python3.7尝试相同的测试,您将看到预期的结果。
如果您想在Python2.7上保持创建顺序,请使用OrderedDict。
https://stackoverflow.com/questions/57621184
复制相似问题