I have a dictonary dumped to json like this
dict({'abc1': {'1': 'asdf', '11': 'asdfasd', "2": 'afds'}, 'abc2': {'1': 'asdf', '11': 'asdfasd', '2': 'afds'}})
How can I dump the dictionary to json with ordered keys.
Because of the alphabetic prefix I can’t use the following code:
import json
d = dict({'2':'two', '11':'eleven'})
json.dumps({int(x):d[x] for x in d.keys()}, sort_keys=True)
Can you give me a hint, how to integrate string based keys in the lines?
Thank you 🙂
2
Answers
The key is to understand how to sort the keys of a dictionary as integers and not in lexigraphical order as strings, because according to that ordering,
'11'
does come before'2'
.Consider:
Fortunately in modern Python (3.6+) dictionaries are insertion ordered, so once this sorting is done, it will remain in the same order.
You can build a list of tuples representing the key/value pairs after converting the key to int.
Then reconstruct the dictionary after sorting
Output: