Reputation: 87
I have below Python dictionary as source
d1 = {
'a': 1,
'b': 2,
'c': [{'d': 3, 'e': 4, 'un': 'wanted1', 'dont': 'needthis1'},
{'d': 5, 'e': 6, 'un': 'wanted2', 'dont': 'needthis2'}]
'xyz': 'abc',
'zxy': 'cab',
'wva': 'xyw'
}
And I want to copy the values of some specific keys to a different dict to form below target
dictionary
d2 = {
'some_attr_1': 1,
'some_attr_x': 2,
'attr_some_z': [{'attr_x': 3, 'attrib': 4},
{'attr_x': 5, 'attrib': 6}]
}
Note:
source
for ex: I don't need keys xyz
, zxy
, etcsource
to be mapped
to different keys in target
dictionary. My current approach is as below to have mapping between source
and target
dictionary keys.
attr_map1 = {
'some_attr_1': 'a',
'some_attr_x': 'b'
}
attr_map2 = {
'attr_x': 'd',
'attrib': 'e',
}
d2 = dict()
for k, v in attr_map1.items():
d2[k] = d1[v]
l1 = list()
for d_elem in d1['c']:
temp_dict = dict()
for k, v in attr_map2.items():
temp_dict[k] = d_elem[v]
l1.append(temp_dict)
d2['attr_some_z'] = l1
Is there any alternate, better and speedy approach to achieve this?
I am looking for a solution in Python 2.7.
thanks,
Upvotes: 0
Views: 105
Reputation: 71461
You can use recursion:
d1 = {'a': 1, 'b': 2, 'c': [{'d': 3, 'e': 4}, {'d': 5, 'e': 6}]}
def build(d):
return {f't_{a}':b if not isinstance(b, (dict, list)) else
list(map(build, b)) if isinstance(b, list) else build(b) for a, b in d.items()}
print(build(d1))
Output:
{
't_a': 1,
't_b': 2,
't_c': [
{'t_d': 3, 't_e': 4},
{'t_d': 5, 't_e': 6}
]
}
Edit: to run this solution in Python2, replace the f-string
with simple concatenation:
d1 = {'a': 1, 'b': 2, 'c': [{'d': 3, 'e': 4}, {'d': 5, 'e': 6}]}
def build(d):
return {'t_'+a:b if not isinstance(b, (dict, list)) else
list(map(build, b)) if isinstance(b, list) else build(b) for a, b in d.items()}
Upvotes: 2