How to sort dictionaries by keys in Python

后端 未结 7 1821
广开言路
广开言路 2020-12-15 05:28

Can anyone tell me how I can sort this:

{\'a\': [1, 2, 3], \'c\': [\'one\', \'two\'], \'b\': [\'blah\', \'bhasdf\', \'asdf\'], \'d\': [\'asdf\', \'wer\', \'a         


        
相关标签:
7条回答
  • 2020-12-15 06:31

    Dicts don't have an order.

    You can call sorted but this just gives you a sorted list of the keys:

    >>> sorted(d)
    ['a', 'b', 'c', 'd']
    

    You can treat it as an iterable and sort the key-value tuples, but then you've just got a list of tuples. That's not the same as a dict.

    >>> sorted(d.items())
    [
     ('a', [1, 2, 3]),
     ('b', ['blah', 'bhasdf', 'asdf']),
     ('c', ['one', 'two']),
     ('d', ['asdf', 'wer', 'asdf', 'zxcv'])
    ]
    

    If you are using Python 2.7 or newer you could also consider using an OrderedDict.

    dict subclass that remembers the order entries were added

    For example:

    >>> d = collections.OrderedDict(sorted(d.items()))
    >>> for k, v in d.items():
    >>>     print k, v
    
    a [1, 2, 3]
    b ['blah', 'bhasdf', 'asdf']
    c ['one', 'two']
    d ['asdf', 'wer', 'asdf', 'zxcv']
    
    0 讨论(0)
提交回复
热议问题