过滤字典列表中的项目

时间:2020-10-29 01:43:30

标签: python list dictionary

在Python中,我希望编辑词典列表,以使它们在每个词典中都具有相同的对应项目。

例如,这是我本来在字典列表中所拥有的:

[{'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}]

我想要的是仅保留带有相应“名称”的字典,但删除所有“准确性”实例。基本上,我希望返回以下内容:

[{'name': 'clock'}, {'name': 'hours'}, {'name': 'nosotros'}, 
{'name': 'pinkfloyd'}, {'name': 'time'}, {'name': 'alarm clock'}, 
{'name': 'analogue'}, {'name': 'clock'}]

请帮助指导我如何做!

3 个答案:

答案 0 :(得分:3)

使用列表理解:

?__tn__=R-R

答案 1 :(得分:1)

如果要以一般方式执行此操作,则可以将字典的键的交集作为交集,然后根据这些键构建新列表:

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

答案 2 :(得分:0)

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