1

I am posting the form and then grabbing the json to form the dict .

myd = \
{'a': {'b': 'c1', 'd': 'f1'},
 'b': {'bb': 'c2', 'dd': 'f2'},
 'c': {'bbb': 'c3', 'ddd': 'f3'}
}

Now I am using josn.loads to convert that into python dict

I am doing this

        headers = DefaultOrderedDict(list, json.loads(request.POST.get('myd')))

Can I do an ordered, default dict in Python?

after doing that my order of the dict gets changed like this

  myd = \
    {'a': {'b': 'c1', 'd': 'f1'},
     'c': {'bbb': 'c3', 'ddd': 'f3'},
     'b': {'bb': 'c2', 'dd': 'f2'},
}

How can I maintain the order?

Community
  • 1
  • 1
user2330497
  • 419
  • 1
  • 7
  • 11
  • 1
    You probably just need a `sorted` call somewhere ... where do you get `DefaultOrderedDict` from?! – wim May 03 '13 at 02:19
  • . I don't want to sort by any key but i just want to have the same order as original That came from here http://stackoverflow.com/questions/6190331/can-i-do-an-ordered-default-dict-in-python – user2330497 May 03 '13 at 02:22

2 Answers2

4

I believe you should do:

json.loads(request.POST.get('myd'), object_pairs_hook=collections.OrderedDict)

You can see some documentation about the object_pairs_hook keyword in the documentation.

Bill Lynch
  • 80,138
  • 16
  • 128
  • 173
0

Purpose of the python dictionary object is to provide you with O(1) access to key value pairs. As a result the dictionary may choose to arrange it in different order for better performance needs. Having said that you can always do something similar to :

for key in sorted(myd.iterkeys()):
    print "%s: %s" % (key, myd[key])
csurfer
  • 296
  • 1
  • 7