1

Hi i have the following code in python:

import json
jsonpost = json.loads('{"Player": {"_id": "3","firstName":"kim","surname":"jones"},"newTable": {"_id": "4","SurName": "abcd"}}')

for key in jsonpost.keys():
    for innerkey in jsonpost[key]:
        print innerkey

my question is why when i print out inner key the order of the keys for jsonpost['Player'] is the following:

_id , surname, firstName
Henrik Andersson
  • 45,354
  • 16
  • 98
  • 92
Kimmy
  • 3,787
  • 5
  • 22
  • 20
  • 3
    Dictionaries aren't ordered in Python. – David Robinson Jul 31 '13 at 15:29
  • 1
    Maps have no specified order, but are merely an association of key to value. Do you need them to be in a particular order? – Dan Lecocq Jul 31 '13 at 15:29
  • Dictionaries usually don't have a guaranteed order. It's an implementation detail, as they're not built to be iterated over. I think Python has a package called "odict" for this purpose. – mpen Jul 31 '13 at 15:29
  • The same is true of JSON (unordered set of key/value pairs) per the spec: http://json.org/ – tuckermi Jul 31 '13 at 15:31

5 Answers5

2

Python dictionaries are implemented internally with a hash table. This means that key order is not preserved. Is this an issue?

Phylogenesis
  • 7,775
  • 19
  • 27
1

keys in a dictionary are never in the same order, if you want them consistently in the same order for your code, you could do

sorted(jsonpost.keys())
Cameron Sparr
  • 3,925
  • 2
  • 22
  • 31
1

Either JavaScript's JSON nor Python's dict have the concept of ordering. You can use collections.OrderedDict in Python to get away with it, but JavaScript does not have such an alternative.

Brian
  • 7,394
  • 3
  • 25
  • 46
0

Python dictionaries are inherently unordered, so when you print them out, the keys can be out of order.

If order is important, you can use an OrderedDict:

import collections
jsonpost = collections.OrderedDict(sorted(jsonpost.items()))

Or you can change to for loop to:

for key in sorted(jsonpost.keys()):
    for innerkey in jsonpost[key]:
        print innerkey
jh314
  • 27,144
  • 16
  • 62
  • 82
0

Dictionary ordering is specified as being unspecified, you could sort(whatever.keys()) or you could use and ordered dictionary, i.e. collections.OrderedDict if you are running python 2.7 or later.

Steve Barnes
  • 27,618
  • 6
  • 63
  • 73