Python: How to sort a dictionary by key

This question already has an answer here:

  • Sorting dictionary keys in python [duplicate] 4 answers
  • How do I sort a dictionary by value? 38 answers
  • How can I sort a dictionary by key? 22 answers

  • Standard Python dictionaries are inherently unordered. However, you could use collections.OrderedDict . It preserves the insertion order, so all you have to do is add the key/value pairs in the desired order:

    In [4]: collections.OrderedDict(sorted(result.items()))
    Out[4]: OrderedDict([('1', 'value1'), ('2', 'value2')])
    

    sorted(result.iteritems(), key=lambda key_value: key_value[0])
    

    This will output sorted results, but the dictionary will remain unsorted. If you want to maintain ordering of a dictionary, use OrderedDict

    Actually, if you sort by key you could skip the key=... part, because then the iterated items are sorted first by key and later by value (what NPE uses in his answer)


    Python dictionaries are unordered (for definition)

    You can use OrderedDict instead

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

    上一篇: 按照最高值排序字典?

    下一篇: Python:如何按键排序字典