I got this dictionary:
[{'id': 1, 'code': 'a'},
{'id': 2, 'code': 'b'},
{'id': 3, 'code': 'c'}]
and I want to change it to:
[{ 1: 'a'},
{2: 'b'},
{ 3: 'c'}]
(python pandas)
CodePudding user response:
a = [{'id': 1, 'code': 'a'},
{'id': 2, 'code': 'b'},
{'id': 3, 'code': 'c'}]
b = []
for dic in a:
b.append({dic['id'] : dic['code']})
print(b)
>>[{1: 'a'}, {2: 'b'}, {3: 'c'}]
CodePudding user response:
One option is with a dictionary comprehension:
[{ent['id']: ent['code']} for ent in a]
[{1: 'a'}, {2: 'b'}, {3: 'c'}]