3 回答
TA贡献1786条经验 获得超12个赞
使用列表理解:
dl = [{'name': 'clock'}, {'name': 'hours'}, {'name': 'nosotros'},
{'name': 'pinkfloyd'}, {'name': 'time'}, {'name': 'alarm clock', 'accuracy': 0.9196},
{'name': 'analogue', 'accuracy': 0.96998}, {'name': 'clock', 'accuracy': 0.99748}]
nl = [{'name': x['name']} for x in dl]
print(nl)
TA贡献1877条经验 获得超6个赞
如果您想以一般方式执行此操作,您可以获取字典中键的交集,然后根据这些键构建一个新列表:
list_o_dicts = [
{'name': 'clock'}, {'name': 'hours'}, {'name': 'nosotros'},
{'name': 'pinkfloyd'}, {'name': 'time'}, {'name': 'alarm clock', 'accuracy': 0.9196},
{'name': 'analogue', 'accuracy': 0.96998}, {'name': 'clock', 'accuracy': 0.99748}
]
common_keys = set.intersection(*map(set, list_o_dicts)) # just {'name'}
output = [{k:d[k] for k in common_keys} for d in list_o_dicts]
输出:
[{'name': 'clock'},
{'name': 'hours'},
{'name': 'nosotros'},
{'name': 'pinkfloyd'},
{'name': 'time'},
{'name': 'alarm clock'},
{'name': 'analogue'},
{'name': 'clock'}]
如果您有多个公用密钥,这仍然有效:
list_o_dicts = [
{'name': 'alarm clock', 'accuracy': 0.9196},
{'name': 'analogue', 'accuracy': 0.96998},
{'name': 'clock', 'accuracy': 0.99748}
]
common_keys = set.intersection(*map(set, list_o_dicts)) # {'accuracy', 'name'}
[{k:d[k] for k in common_keys} for d in list_o_dicts]
出去:
[{'accuracy': 0.9196, 'name': 'alarm clock'},
{'accuracy': 0.96998, 'name': 'analogue'},
{'accuracy': 0.99748, 'name': 'clock'}]
TA贡献1831条经验 获得超9个赞
in_list = [{'name': 'clock'}, {'name': 'hours'}, {'name': 'nosotros'},
{'name': 'pinkfloyd'}, {'name': 'time'}, {'name': 'alarm clock', 'accuracy': 0.9196},
{'name': 'analogue', 'accuracy': 0.96998}, {'name': 'clock', 'accuracy': 0.99748}]
new_list = [{k: v for k,v in ele.items() if k == 'name'} for ele in in_list]
print(new_list)
输出:
[{'name': 'clock'}, {'name': 'hours'}, {'name': 'nosotros'}, {'name': 'pinkfloyd'}, {'name': 'time'}, {'name': 'alarm clock'}, {'name': 'analogue'}, {'name': 'clock'}]
添加回答
举报