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.
from collections import defaultdict
nestdict = defaultdict(dict)
nestdict[mydict['id']] = mydict[['name'],['age'],['city']]
nestdict
CodePudding user response:
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'}}
CodePudding user response:
You can make a copy of your dictionary to preserve the original one:
temp_dict = mydict.copy()
temp_dict.pop('id')
nested_dict = {'id': mydict['id'], 'data': temp_dict}
print(nested_dict)
The output:
{'id': '123', 'data': {'name': 'Bob', 'age': '30', 'city': 'LA'}}