【发布时间】:2019-11-30 11:32:42
【问题描述】:
我写了这段代码:
words_dict = {}
my_list = ["a", "b", "c", "d", "e"]
for st in my_list:
words_dict.update({st: 0})
print words_dict
我期望的输出是:
{'a': 0, 'b': 0, 'c': 0, 'd': 0, 'e': 0}
但我明白了
{'a': 0, 'c': 0, 'b': 0, 'e': 0, 'd': 0}
为什么会发生这种情况,我怎样才能获得{'a':0, 'b':0, 'c':0, 'd':0, 'e':0}?
【问题讨论】:
-
字典本质上是无序的。注意,你不应该对单个值使用更新,使用
words_dict[st] = 0 -
如果您必须按字母顺序使用字典中的值,然后获取键,对它们进行排序并使用它们来获取值。
标签: python list python-2.7 dictionary