玖叶教程网

前端编程开发入门

Python第89题:从字典中删除一组键【PythonTip题库精编300题】

1、编程试题:

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

定义函数remove_keys(),有两个参数:字典dict_input和键列表key_list。

在函数中,从字典中删除key_list中存在的所有键。

返回更新后的字典。

示例输入

{"fruit": "Apple", "color": "Red", "price": 10}

color price

示例输出

{'fruit': 'Apple'}

解释:

在这里,列表color和price是字典中存在的指定键,需要被删除。因此,最终更新后的字典不包含color和price。

2、代码实现:

可编辑代码如下:

#!/usr/bin/python3.9
# -*- coding: utf-8 -*-
#
# Copyright (C) 2024 , Inc. All Rights Reserved
#
# @Time      : 2024/2/1 21:26
# @Author    : fangel
# @FileName  : 89. 从字典中删除一组键.py
# @Software  : PyCharm

def remove_keys(dict_input, key_list):
    # #方法1:针对key_list中的key为基点进行字典中键的删除
    # for key in key_list:
    #     tmp = dict_input.pop(key)
    # return dict_input
    #方法2:定义一个字典,将不在key_list中的key值都加入到该字典中,并返回该字典
    resDict = {}
    for key,value in dict_input.items():
        if key not in key_list:
            resDict[key] = value
    return resDict

# 获取输入
user_dict = eval(input())
user_key_list = input().split()
# 调用函数
print(remove_keys(user_dict, user_key_list))

3、代码分析:

本例提供了两种方法,方法一,针对key_list中的key为基点进行字典中键的删除,方法二,定义一个字典,将不在key_list中的key值都加入到该字典中,并返回该字典

4、运行结果:

输入:

{"book": "Python", "author": "Guido", "year": 1990}

year

输出:

{'book': 'Python', 'author': 'Guido'}

发表评论:

控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言