pythontip 从字典中删除一组键

编写一个程序,使用提供的键列表从字典中删除指定的键集合。

定义函数remove_keys(),有两个参数:字典dict_input和键列表key_list。
在函数中,从字典中删除key_list中存在的所有键。
返回更新后的字典。
示例输入
{"fruit": "Apple", "color": "Red", "price": 10}
color price
示例输出

  • 使用del语句删除字典中的键,如果键不存在,则会引发KeyError异常。需要考虑下异常。
    使用pop方法删除字典中的键,如果键不存在,则不会引发异常,建议用此方法。
点击查看代码
def remove_keys(dict_input, key_list):
    for i in key_list:
        dict_input.pop(i)
    return dict_input

# 获取输入 
user_dict = eval(input())
user_key_list = input().split()

# 调用函数 
print(remove_keys(user_dict, user_key_list))
posted @ 2025-11-15 20:25  硫酸钡barit  阅读(10)  评论(0)    收藏  举报