Swapping the first two keys of dictionary

I have the following dictionary, I want to swap ‘path’ and ‘outputs’, so that path appears first

 {'outputs': {'path': 'abc.jpg',     'size': {'width': 1920, 'height': 1080, 'depth': 3},     'object': [{'name': 'vehicle',     'pose': 'Unspecified',     'truncated': 0,     'difficult': 0,     'bndbox': {'xmin': 1532, 'ymin': 631, 'xmax': 1657, 'ymax': 687}},      {'name': 'vehicle',     'pose': 'Unspecified',     'truncated': 0,     'difficult': 0,     'bndbox': {'xmin': 795, 'ymin': 685, 'xmax': 880, 'ymax': 723}},      {'name': 'vehicle',     'pose': 'Unspecified',     'truncated': 0,     'difficult': 0,     'bndbox': {'xmin': 1473, 'ymin': 660, 'xmax': 1529, 'ymax': 690}}]}} 

like this

{'path': 'abc.jpg','outputs': {     'size': {'width': 1920, 'height': 1080, 'depth': 3},     'object': [{'name': 'vehicle',     'pose': 'Unspecified',     'truncated': 0,     'difficult': 0,     'bndbox': {'xmin': 1532, 'ymin': 631, 'xmax': 1657, 'ymax': 687}},      {'name': 'vehicle',     'pose': 'Unspecified',     'truncated': 0,     'difficult': 0,     'bndbox': {'xmin': 795, 'ymin': 685, 'xmax': 880, 'ymax': 723}},      {'name': 'vehicle',     'pose': 'Unspecified',     'truncated': 0,     'difficult': 0,     'bndbox': {'xmin': 1473, 'ymin': 660, 'xmax': 1529, 'ymax': 690}}]}} 

This dictionary is obtained by loading a json string. Is there some way of swapping the first two keys of this dictionary?

Asked on July 15, 2020 in Python.
Add Comment
1 Answer(s)

Use pop to remove the path from withing outputs and create a new toplevel key path to store the removed value.

dict = json.loads(...) dict["path"] = dict["outputs"].pop("path") 

Note that it would place path to the same level as output, but it doesn’t have to appear first, as keys of a dictionary are unordered.

Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.