skip to Main Content
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


  1. 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:

    >>> d = {'1': 'asdf', '11': 'asdfasd', "2": 'afds'}
    >>> {k: d[k] for k in sorted(d.keys(), key=int)}
    {'1': 'asdf', '2': 'afds', '11': 'asdfasd'}
    

    Fortunately in modern Python (3.6+) dictionaries are insertion ordered, so once this sorting is done, it will remain in the same order.

    Login or Signup to reply.
  2. You can build a list of tuples representing the key/value pairs after converting the key to int.

    Then reconstruct the dictionary after sorting

    d = {
        "abc1": {"1": "asdf", "11": "asdfasd", "2": "afds"},
        "abc2": {"1": "asdf", "11": "asdfasd", "2": "afds"}
    }
    
    for k, v in d.items():
        t = [(int(_k), _v) for _k, _v in v.items()]
        d[k] = {str(_k): _v for _k, _v in sorted(t)}
    
    print(d)
    

    Output:

    {'abc1': {'1': 'asdf', '2': 'afds', '11': 'asdfasd'}, 'abc2': {'1': 'asdf', '2': 'afds', '11': 'asdfasd'}}
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search