How to sort dictionaries by keys in Python

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

    As the other answer mentioned, the order of a dictionary's keys is arbitrary and you shouldn't rely on it.

    If you're using Python 2.7 or 3.1 or later, try out collections.OrderedDict (2.7 docs; 3.1 docs; also see PEP 372). There's a link in the docs to a pure-Python version of OrderedDict that works on earlier Python versions.

提交回复
热议问题