[英]Python: select key, values from dictionary corresponding to given list
我有一個這樣的字典:
d = {'cat': 'one', 'dog': 'two', 'fish': 'three'}
給定一個列表,我可以只保留給定的鍵值嗎?
輸入:
l = ['one', 'three']
Output:
new_d = {'cat': 'one', 'fish': 'three'}
您可以使用字典理解來輕松實現此目的:
{k: v for k, v in d.items() if v in l}
您上面描述的場景為IN運算符提供了一個完美的用例,它測試一個值是否是集合的成員,例如列表。
下面的代碼是為了演示這個概念。 對於更實際的應用,請查看字典理解。
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)
Output 是:
{'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)
Output 是:
{'cat': 'one', 'dog': 'two', 'fish': 'three'}
{'cat': 'one', 'fish': 'three'}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.