You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用自定义函数在Python中检查字典的键和值是否存在

在Python中用自定义函数检查字典的键和值是否存在

检查键是否存在

我们可以封装一个自定义函数来替代原生的in dict.keys()写法,逻辑和示例一致,但复用性更强:

def check_key_exists(target_dict, key):
    if key in target_dict:
        # 直接用in判断字典本身等价于判断键是否存在,比.keys()更高效
        print('Exists!')
    else:
        print("Doesn't exist!")

# 测试示例
info = {'Breakfast': 'Egg', 'time': '05:30 am'}
check_key_exists(info, 'lunch')  # 输出: Doesn't exist!
check_key_exists(info, 'Breakfast')  # 输出: Exists!

注:直接用key in target_dict和key in target_dict.keys()效果一致,但前者性能更优,因为不需要生成额外的键视图对象。

检查值是否存在

如果需要检查值是否存在,同样可以封装自定义函数:

def check_value_exists(target_dict, value):
    if value in target_dict.values():
        print('Exists!')
    else:
        print("Doesn't exist!")

# 测试示例
check_value_exists(info, 'Egg')  # 输出: Exists!
check_value_exists(info, 'Bread')  # 输出: Doesn't exist!

通用检查函数(可选)

如果想要一个函数同时支持检查键或值,可以加个参数区分:

def check_dict_item(target_dict, item, check_type='key'):
    if check_type == 'key':
        exists = item in target_dict
    elif check_type == 'value':
        exists = item in target_dict.values()
    else:
        print('Invalid check type! Use "key" or "value"')
        return
    print('Exists!' if exists else "Doesn't exist!")

# 测试
check_dict_item(info, 'time', 'key')  # 输出: Exists!
check_dict_item(info, '05:30 am', 'value')  # 输出: Exists!

内容的提问来源于stack exchange,提问作者montegu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 20:30:56