在 Python 中从字典中排除特定键
Exclude specific keys from a Dictionary in Python
从字典中排除特定键:
- 使用该
dict.items()
方法获取字典项目的视图。 - 使用字典理解来迭代项目。
- 从字典中排除指定的键。
主程序
my_dict = { 'id': 1, 'name': 'bobbyhadz', 'age': 30, 'language': 'python' } def exclude_keys(dictionary, keys): return { key: value for key, value in dictionary.items() if key not in keys } result = exclude_keys(my_dict, ['id', 'age']) print(result) # 👉️ {'name': 'bobbyhadz', 'language': 'python'} result = exclude_keys(my_dict, ['id', 'language']) print(result) # 👉️ {'name': 'bobbyhadz', 'age': 30}
dict.items方法返回字典
项((键,值)对)的新视图。
主程序
my_dict = { 'id': 1, 'name': 'bobbyhadz', 'age': 30, 'language': 'python' } # 👇️ dict_items([('id', 1), ('name', 'bobbyhadz'), ('age', 30), ('language', 'python')]) print(my_dict.items())
我们使用字典理解来迭代视图。
字典理解与列表理解非常相似。
他们对字典中的每个键值对执行一些操作,或者选择满足条件的键值对的子集。
On each iteration, we use the not in
operator to check if the current key is
not in the list of keys to exclude.
main.py
def exclude_keys(dictionary, keys): return { key: value for key, value in dictionary.items() if key not in keys }
The
in operator
tests for membership. For example, x in l
evaluates to True
if x
is a
member of l
, otherwise it evaluates to False
.
x not in l
returns the negation of x in l
.The exclude_keys
function returns a new dictionary that doesn’t contain the
specified keys.
If you need to remove the keys from the original dictionary, use the
dict.pop()
method in a for
loop.
main.py
my_dict = { 'id': 1, 'name': 'bobbyhadz', 'age': 30, 'language': 'python' } keys_to_remove = ['id', 'age'] for key in keys_to_remove: my_dict.pop(key, None) print(my_dict) # 👉️ {'name': 'bobbyhadz', 'language': 'python'}
We used a for
loop to iterate over the keys to be removed.
On each iteration, we use the dict.pop()
method to remove the key from the
dictionary.
如果字典中不存在指定的键,则该dict.pop()
方法采用要返回的默认值。
如果您不提供默认值并且键不在字典中,
KeyError
则会引发 a 。