Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python Dict: Keep first column , and make the rest as nested dict

Given the following dict:

mydict={'id': '123', 'name': 'Bob', 'age': '30','city': 'LA'}

I would like to transform this dictionary into a nested dict, where "id" key is kept, but all other (arbitary) keys are then packed into a nested dict. Hence the output should be like:

nestdict={'id':'123','data':{'name': 'Bob', 'age': '30','city': 'LA'}}

What I have tried was using dict.pop but this returns a list , and also using defaultdict from collections, but this did not work.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

from collections import defaultdict
nestdict = defaultdict(dict)
nestdict[mydict['id']] = mydict[['name'],['age'],['city']]
nestdict

>Solution :

If you don’t want to mutate the original mydict,

>>> mydict = {'id': '123', 'name': 'Bob', 'age': '30','city': 'LA'}
>>> d = {'id': mydict['id'], 'data': {k: v for k, v in mydict.items() if k != "id"}}
{'id': '123', 'data': {'name': 'Bob', 'age': '30', 'city': 'LA'}}

If mutating mydict (since we pop out id) is OK,

>>> mydict = {'id': '123', 'name': 'Bob', 'age': '30','city': 'LA'}
>>> d = {'id': mydict.pop('id'), 'data': mydict}
{'id': '123', 'data': {'name': 'Bob', 'age': '30', 'city': 'LA'}}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading