【问题标题】:Sorting Dict throws an error - python [duplicate]排序字典引发错误-python [重复]
【发布时间】:2017-01-07 22:47:29
【问题描述】:

我正在学习 python 并尝试以最简单的方式对 dicts 及其抛出错误进行排序

d = {'a':10,'b':1,'c':22}
print (d.items())

t = d.items()
t.sort()
print (t)

它抛出了下面的错误

dict_items([('b', 1), ('a', 10), ('c', 22)])
Traceback (most recent call last):
  File "/Users/bash/Downloads/n.py", line 5, in <module>
    t.sort()
AttributeError: 'dict_items' object has no attribute 'sort'

是的,我用谷歌搜索了,stackoverflow 没有给出我正在寻找的结果,所以如果你不反对这个问题并尽可能给出答案,那就太好了。

【问题讨论】:

    标签: python


    【解决方案1】:

    字典没有sort 属性。您可以使用 sorted 按键对其进行排序:

    for key in sorted(d.iterkeys()):
        print("%s: %s" % (key, d[key]))
    

    【讨论】:

    • 我还要注意 sorted() 可以与 dict_item 对象一起使用,所以所有询问者真正需要对他的代码做的就是将 t.sort() 更改为 t = sorted(t)
    【解决方案2】:

    事情是这样的,你的原始代码在 python 2.x 中工作:

    d = {'a': 10, 'b': 1, 'c': 22}
    print(d.items())
    
    t = d.items()
    t.sort()
    print(t)
    

    因为 d.items() 返回一个 &lt;type 'list'&gt; 类,但在 python 3.x 中没有,在 python 3.x 中它返回 &lt;class 'dict_items'&gt;,它没有排序方法,所以可能的解决方法是这样做:

    d = {'a': 10, 'b': 1, 'c': 22}
    
    t = list(d.items())
    print(t)
    t.sort()
    print(t)
    

    如您所见,将 d.items() 转换为 list 将允许您使用 list.sort

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-21
      • 2018-02-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多