Python - how to insert an element at the beginning of a dictionary?

I know there is no order in a Python dictionary, but I have a JSON file containing dictionaries and I want to insert an item into each dictionary. This way, when I open the JSON, I see the added element at the top.

Example: JSON file contains:

{"b": 2, "c": 3}

It should be like this after adding:

{"a": 1, "b": 2, "c": 3}

+3


source to share


1 answer


For this you can use a little trick with OrderedDict

.

Step 1. Save your old data.

import json 
s = {"b":2, "c":3}
json.dump(s, open('file.json', 'w'))

      

The data looks like this: '{"b": 2, "c": 3}'



Step 2. When adding new data, use OrderedDict

to load existing data.

from collections import OrderedDict

new_data = OrderedDict({'a' : 1})
new_data.update(json.loads(open('file.json'), object_pairs_hook=OrderedDict))
json.dump(new_data, open('file.json', 'w'))

      

And now the data looks like this: '{"a": 1, "b": 2, "c": 3}'

+3


source







All Articles