【问题标题】:Python looping does not return data in an expected order [duplicate]Python循环不按预期顺序返回数据[重复]
【发布时间】:2013-12-19 14:39:58
【问题描述】:

我是 Python 新手。

这里我定义了一个字典:

dic = {"hello":"is_done", "bye":'is_gone', "things":'thinking'};

然后我遍历它以使其按预期返回数据:

for item in dic : 
 print("this is an item from our dictionary: "+dic[item]);

这是输出:

this is an item from our dictionary: is_gone
this is an item from our dictionary: thinking
this is an item from our dictionary: is_done

为什么生成输出的迭代顺序与字典对象中 key:value 对的初始化顺序不同?

【问题讨论】:

  • 同意重复,但这个答案可以改进:)。记住字典中的键是一个集合,而不是一个列表。
  • 字典没有以任何明显的方式排序,这就是为什么这些值打印的顺序与您预期的不符。查看 Eric 提供的链接以获取更多信息。
  • 谢谢我现在知道了。非常感谢

标签: python dictionary iteration


【解决方案1】:

正如一些 cmets 已经指出的那样:python 中的内置 dicts 是无序的,人们不能对迭代时出现的内容的顺序做出假设。如果您需要订购,请使用Ordered Dicts

保持字典的顺序需要额外的插入成本,对于大多数应用程序来说,通常不需要它。这就是为什么基本的不关心它的原因。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-07
    • 2013-07-21
    • 1970-01-01
    • 2017-08-24
    • 2020-09-02
    • 2020-01-13
    • 1970-01-01
    相关资源
    最近更新 更多