为什么排序(字典)返回一个列表而不是字典?

这个问题在这里已经有了答案:

  • 如何按价值对字典进行排序? 38个答案

  • 请记住,词典是无序的。 所以你可以想象如果字典被排序并返回字典会发生什么。

    要对字典键和值进行排序,您应该使用:

    sorted(phoneBook.items())
    

    在字典上调用iterator自然会返回唯一的键列表。 .items()确保返回键和值。

    为了在排序后保持顺序,将得到的元组列表(通过sorted返回)放入OrderedDict

    from collections import OrderedDict
    
    phonebook_sorted = OrderedDict(sorted(phoneBook.items()))
    

    是不是排序的字典仍然是一个字典,除了键的顺序改变?

    内置的sorted函数接受一个可迭代的输入并返回一个列表 - 总是。

    对于一个dict ,迭代它会产生密钥,所以sorted只是对键sorted排序。 如果你想对键值进行排序,那么:

    sorted(phoneBook.items())
    

    你仍然会得到一个列表,但它将是一个键 - 值对列表(作为元组)。

    链接地址: http://www.djcxy.com/p/18169.html

    上一篇: Why sorted(dictionary) returns a list instead of dictionary?

    下一篇: Sorting dictionary by values without losing information of keys