0

I face a problem when reading a JSON file from a Python script. Here is the JSON file:

{
    "a": 1,
    "b": 2,
    "c": 3, 
    "d": 4, 
    "e": 5, 
    "f": 6, 
    "g": 7, 
    "h": 8, 
    "i": 9
}

and this is the Python file on where I open the JSON file from the current path and read every values associated with the letter in it:

with open(os.getcwd() + '/letters.json') as lettersListJSON:
    lettersList = json.load(lettersListJSON)
    for char in lettersList
        print lettersList[char]

I strangely get this output:

1
3
2
5
4
7
6
9
8

Why are these values interlaced and how can I prevent this from happening ? Should I lock the access of the variable with a mutex?

ooj-001
  • 180
  • 9
  • 2
    this is not so strange.. json.load returns a dict, dicts are not sorted. – Christian Sloper Apr 12 '19 at 13:07
  • 1
    Dictionarys do not have order. Only for python 3.7 insert order is guaranteed and ipython 3.6 had this as sideeffect. You do not know how they are inserted ... so it might the insertorder. Use `for char in sorted(lettersList):` if you want key output sorted by key – Patrick Artner Apr 12 '19 at 13:08
  • Possible dupe: https://stackoverflow.com/questions/35609991/how-do-i-print-a-sorted-dictionary-in-python-3-4-3?rq=1 (for the print sorting part) - not for how json creates a dict or https://stackoverflow.com/questions/1479649/readably-print-out-a-python-dict-sorted-by-key or – Patrick Artner Apr 12 '19 at 13:10
  • @ChristianSloper Thank you very much ! I didn't know json.load returned an unsorted dictionary. – ooj-001 Apr 12 '19 at 13:14
  • Possible duplicate of [Are dictionaries ordered in Python 3.6+?](https://stackoverflow.com/questions/39980323/are-dictionaries-ordered-in-python-3-6) – Bob Dalgleish Apr 12 '19 at 13:53

2 Answers2

4

The letterList is actually a letterDict so it isn't ordered.

You can load the JSON into an OrderedDict if you really want it to be in order:

from  collections import OrderedDict

letters = json.load(letterslistJSON, object_pairs_hook=OrderedDict)   

(obviously I omitted opening the file and such)

1

Your output is not interlaced because of any "threading" issues. Dictionarys before python 3.6 are not sorted, CPython introduced insert order sorting based on a implementation detail with 3.5 and from Python 3.7 on insert order it guaranteeed by default.

More informations:

You do not know how json.load creates the dictionary - if you want your output sorted - sort it:

t = """{
    "a": 1,
    "b": 2,
    "c": 3, 
    "d": 4, 
    "e": 5, 
    "f": 6, 
    "g": 7, 
    "h": 8, 
    "i": 9
}"""

import json

lettersList = json.loads(t)
for char in lettersList:
    print lettersList[char]

lettersList = json.loads(t)
for char in sorted(lettersList):    # sort your keys before printing
    print lettersList[char]

Output:

# not sorted
1
3
2
5
4
7
6
9
8

# sorted keys
1
2
3
4
5
6
7
8
9
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69