如何只保留字典的第二项并在输出中保持相同的格式(字典列表(?
a = [{'a1':10,'b1':9},{'d1':10,'c1':9}]
预期输出
e = [{'b1':9},{'c1':9}]
我尝试过的代码:
e = [dict(b.items())[1] for a in e] #not getting o/p
不是很漂亮,但应该可以工作:
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}]
不过,请记住,它应该只适用于Python 3.7和更新版本,如这里所解释的。
我将使用列表理解
代码:
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)
结果:
[{'b1': 9}, {'c1': 9}]