prog
prog

Reputation: 1073

take the second or nth element of dictionary in a list

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

Answers (2)

Rafa
Rafa

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

leaf_soba
leaf_soba

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

Related Questions