Python:选择键,从对应于给定列表的字典中选择值
我有一套这样的字典:Python:选择键,从对应于给定列表的字典中选择值,python,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} 您可以使用字典理解轻松实现这一点: {k: v for k, v in d.it
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}
您可以使用字典理解轻松实现这一点:
{k: v for k, v in d.items() if v in l}
您可以复制字典并删除不需要的元素:
d = {'cat': 'one', 'dog': 'two', 'fish': 'three'}
l = ['one', 'three']
new_d = d.copy()
for element in d:
if (d[element]) not in l:
new_d.pop(element)
print(d)
print(new_d)
输出为:
{'cat': 'one', 'dog': 'two', 'fish': 'three'}
{'cat': 'one', 'fish': 'three'}
{'cat': 'one', 'fish': 'three'}
您可以复制字典并删除不需要的元素:
d = {'cat': 'one', 'dog': 'two', 'fish': 'three'}
l = ['one', 'three']
new_d = d.copy()
for element in d:
if (d[element]) not in l:
new_d.pop(element)
print(d)
print(new_d)
输出为:
{'cat': 'one', 'dog': 'two', 'fish': 'three'}
{'cat': 'one', 'fish': 'three'}
{'cat': 'one', 'fish': 'three'}
上面描述的场景为操作符提供了一个完美的用例,用于测试值是否是集合(如列表)的成员 下面的代码是为了演示这个概念。有关更多实际应用,请查看字典理解
d = {'cat': 'one', 'dog': 'two', 'fish': 'three'}
l = ['one', 'three']
d_output = {}
for k,v in d.items(): # Loop through input dictionary
if v in l: # Check if the value is included in the given list
d_output[k] = v # Assign the key: value to the output dictionary
print(d_output)
输出为:
{'cat': 'one', 'dog': 'two', 'fish': 'three'}
{'cat': 'one', 'fish': 'three'}
{'cat': 'one', 'fish': 'three'}
上面描述的场景为操作符提供了一个完美的用例,用于测试值是否是集合(如列表)的成员 下面的代码是为了演示这个概念。有关更多实际应用,请查看字典理解
d = {'cat': 'one', 'dog': 'two', 'fish': 'three'}
l = ['one', 'three']
d_output = {}
for k,v in d.items(): # Loop through input dictionary
if v in l: # Check if the value is included in the given list
d_output[k] = v # Assign the key: value to the output dictionary
print(d_output)
输出为:
{'cat': 'one', 'dog': 'two', 'fish': 'three'}
{'cat': 'one', 'fish': 'three'}
{'cat': 'one', 'fish': 'three'}