How to sort dictionaries by keys in Python

后端 未结 7 1848
广开言路
广开言路 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:12

    It's worth noting that Python has a number of dictionary implementations that maintain the keys in sorted order. Consider the sortedcontainers module which is pure-Python and fast-as-C implementations. There's a performance comparison with other fast and feature-complete implementations benchmarked against one another.

    For example:

    >>> from sortedcontainers import SortedDict
    >>> d = {'a': [1, 2, 3], 'c': ['one', 'two'], 'b': ['blah', 'bhasdf', 'asdf'], 'd': ['asdf', 'wer', 'asdf', 'zxcv']}
    >>> s = SortedDict(**d)
    >>> s.keys()
    SortedSet(['a', 'b', 'c', 'd'])
    

    You can also entirely replace your use of dict with SortedDict as it supports fast get/set operations and sorted iterations of items by key.

提交回复
热议问题