'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.
from collections import defaultdict
nestdict = defaultdict(dict)
nestdict[mydict['id']] = mydict[['name'],['age'],['city']]
nestdict
Solution 1:[1]
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'}}
Solution 2:[2]
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'}}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | AKX |
| Solution 2 |
