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?

2
  • 1
    You probably just need a sorted call somewhere ... where do you get DefaultOrderedDict from?! Commented May 3, 2013 at 2: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 stackoverflow.com/questions/6190331/… Commented May 3, 2013 at 2:22

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.