Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/352.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:选择键,从对应于给定列表的字典中选择值_Python - Fatal编程技术网

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