skip to Main Content

I made the following dict:

    logs = {
    '3h forecast': {
        'Ort': '',
        'Datum und Uhrzeit': '',
        'Temperatur': '',
        'Temperatur_Min': '',
        'Temperatur_Max': ''},

    '6h forecast': {
        'Ort': '',
        'Datum und Uhrzeit': '',
        'Temperatur': '',
        'Temperatur_Min': '',
        'Temperatur_Max': ''},

    '9h forecast': {
        'Ort': '',
        'Datum und Uhrzeit': '',
        'Temperatur': '',
        'Temperatur_Min': '',
        'Temperatur_Max': ''},

    '12h forecast': {
        'Ort': '',
        'Datum und Uhrzeit': '',
        'Temperatur': '',
        'Temperatur_Min': '',
        'Temperatur_Max': ''}
}

and print it with following line:

print(json.dumps(logs, sort_keys=True, indent=4))

and the result in the console is this:

{
"12h forecast": {
"Datum und Uhrzeit": "",
"Ort": "",
"Temperatur": "",
"Temperatur_Max": "",
"Temperatur_Min": ""
},
"3h forecast": {
"Datum und Uhrzeit": "",
"Ort": "",
"Temperatur": "",
"Temperatur_Max": "",
"Temperatur_Min": ""
},
"6h forecast": {
"Datum und Uhrzeit": "",
"Ort": "",
"Temperatur": "",
"Temperatur_Max": "",
"Temperatur_Min": ""
},
"9h forecast": {
"Datum und Uhrzeit": "",
"Ort": "",
"Temperatur": "",
"Temperatur_Max": "",
"Temperatur_Min": ""
}
}

So… Why is the 12h forecast now on the first place and not like the logs dict on the last place?

What am I doing wrong? 🙂

2

Answers


  1. just remove sort_keys=True

    print(json.dumps(logs, indent=4))
    

    #output

    {
        "3h forecast": {
            "Ort": "",
            "Datum und Uhrzeit": "",
            "Temperatur": "",
            "Temperatur_Min": "",
            "Temperatur_Max": ""
        },
        "6h forecast": {
            "Ort": "",
            "Datum und Uhrzeit": "",
            "Temperatur": "",
            "Temperatur_Min": "",
            "Temperatur_Max": ""
        },
        "9h forecast": {
            "Ort": "",
            "Datum und Uhrzeit": "",
            "Temperatur": "",
            "Temperatur_Min": "",
            "Temperatur_Max": ""
        },
        "12h forecast": {
            "Ort": "",
            "Datum und Uhrzeit": "",
            "Temperatur": "",
            "Temperatur_Min": "",
            "Temperatur_Max": ""
        }
    }
    
    Login or Signup to reply.
  2. What happened here is that you were sorting the keys based on strings.
    So the '1' from '12' got compared with the '3' from the other forecast.
    And because '1' is lower than '3' in the ASCII table it is placed earlier in the list.

    You can check this behavior yourself by comparing

    '9' < '10'
    

    to

    9 < 10
    

    To prevent this is in this specific case you can remove the sort_keys attribute.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search