Reputation: 1073
How to keep only 2nd items of dictionary and preserve the same format(list of dictionaries) in the output?
a = [{'a1':10,'b1':9},{'d1':10,'c1':9}]
Expected output
e = [{'b1':9},{'c1':9}]
Code i tried:
e = [dict(b.items())[1] for a in e] #not getting o/p
Upvotes: 0
Views: 2547
Reputation: 684
Not very pretty, but should be working:
new_dict = dict()
for i in (a):
new_dict[list(i.items())[1][0]] = list(i.items())[1][1]
print([new_dict])
>> [{'b1': 9, 'c1': 9}]
Please keep in mind though, that it should be working only for Python 3.7 and newer versions, as explained here.
Upvotes: 2
Reputation: 2518
I'll use list comprehension
code:
a = [{'a1':10,'b1':9},{'d1':10,'c1':9}]
e = [{list(ele.items())[1][0]:list(ele.items())[1][1]} for ele in a]
print(e)
result:
[{'b1': 9}, {'c1': 9}]
Upvotes: 1