Why sorted(dictionary) returns a list instead of dictionary?
This question already has an answer here:
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