0

How can I get keys in the first level in JSON in the same order as it is passed from angular js? Let's say bellow example.

my_dict = {
            'key1': {...},
            'key2': {...},
            'key3': {...}
          }

Now when I fetch first level keys in python, it is not giving me in the same order as passed. But for some reason, I want to fetch it in the same order as passed.

for item in my_dict:
     print item

This gives bellow result.

key3
key2
key1

Q1 - Why python change it's order?

Q2 - For some reason i want it in the same order like ['key1','key2','key3']. How can I fetch it?

I tried lots of thing on internet but not getting the solution. Downvoters give the reason, so I can improve my question.

Mayur Patel
  • 1,741
  • 15
  • 32
  • Possible duplicate of [Can internal dictionary order change?](http://stackoverflow.com/questions/38975722/can-internal-dictionary-order-change) – shad0w_wa1k3r Feb 06 '17 at 12:07

2 Answers2

0

Because python's dicts are hashed tables. The nature of hashed tables is that they do not keep the initial ordering. Check this link to learn more.

In order to keep your dict in certain order consider using OrderedDict

Example from python docs on this:

>>> # regular unsorted dictionary
>>> d = {'banana': 3, 'apple': 4, 'pear': 1, 'orange': 2}

>>> # dictionary sorted by key
>>> OrderedDict(sorted(d.items(), key=lambda t: t[0]))
OrderedDict([('apple', 4), ('banana', 3), ('orange', 2), ('pear', 1)])
Denis Olehov
  • 192
  • 2
  • 12
0

Dictionary is a key-value map. It does not guarantee order. Use OrderedDict

Community
  • 1
  • 1
kawadhiya21
  • 2,458
  • 21
  • 34