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
just remove
sort_keys=True
#output
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
to
To prevent this is in this specific case you can remove the
sort_keys
attribute.