Why sorted(dictionary) returns a list instead of dictionary?

This question already has an answer here:

  • How do I sort a dictionary by value? 38 answers

  • Keep in mind that dictionaries are unordered. So you can imagine what will happen if the dictionary got sorted and a dictionary was returned.

    To sort the dictionary keys and values you should use:

    sorted(phoneBook.items())
    

    Calling an iterator on a dictionary will naturally return only its list of keys. .items() ensures both keys and values are returned.

    To keep the order after sorting, put the resulting list of tuples (returned by sorted ) in an OrderedDict :

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

    isn't the sorted dictionary still a dictionary, except the sequence of the keys are changed?

    No. The builtin sorted function accepts an iterable as input and returns a list -- Always.

    For a dict , iterating over it yields the keys and so sorted just sorts the keys. If you want to sort the keys an values, then do:

    sorted(phoneBook.items())
    

    You'll still get a list, but it'll be a list of key-value pairs (as tuples).

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

    上一篇: 在Python中使用** kwargs的正确方法

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