Python:从与给定列表对应的字典中选择键、值
我有一个像这样的字典:
d = {'cat': 'one', 'dog': 'two', 'fish': 'three'}
给定一个列表,我可以只保留给定的键值吗?
输入:
l = ['one', 'three']
输出:
new_d = {'cat': 'one', 'fish': 'three'}
回答
您可以使用字典理解来轻松实现这一点:
{k: v for k, v in d.items() if v in l}