change dict in pandas

Viewed 30

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)

2 Answers
 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'}]

One option is with a dictionary comprehension:

[{ent['id']: ent['code']} for ent in a]
[{1: 'a'}, {2: 'b'}, {3: 'c'}]
Related