Can anyone tell me how I can sort this:
{\'a\': [1, 2, 3], \'c\': [\'one\', \'two\'], \'b\': [\'blah\', \'bhasdf\', \'asdf\'], \'d\': [\'asdf\', \'wer\', \'a
Here is a quick and easy function you can use to sort a dictionary by keys.
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
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)
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