How to sort dictionaries by keys in Python

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

    Here is a quick and easy function you can use to sort a dictionary by keys.

    Put this code in a separate file called sdict.py:

    def sortdict(dct):
        kys = dct.keys()
        kys.sort()
        from collections import OrderedDict
        d = OrderedDict()
        for x in kys: 
            for k, v in dct.iteritems():
                if (k == x):
                    d[k] = v
        return d
    

    Now, place this code into a separate file called test.py to test it with a sample dictionary:

    from sdict import sortdict
    import json
    dct = {'sizes':[32,28,42], 'dog':'schnauser', 'cat':'siamese', 'bird':'falcon'}
    dctx = sortdict(dct)
    print json.dumps(dctx) 
    

    And finally, call test.py from the command line:

    $ python test.py
    {"bird": "falcon", "cat": "siamese", "dog": "schnauser", "sizes": [32, 28, 42]}
    

    I'm only using json.dumps line to show you that it's an actual dictionary, and not just a string representation. You can also test it with the type() function for that matter.

    I included a nested list with numeric values in the sample dictionary to show that the function can handle more complex dictionaries, not just single-layer string-based dicts.

    The code is pretty straightforward, so it would be easy to modify it to sort by values, if that's your preference - although sorting by value would not make sense if some of the values are objects, like lists, tuples or other dicts.

    Admittedly, this only works in python 2.7 or later.

    Cheers,
    -=Cameron

提交回复
热议问题