如何在python字典中检查键和值的条件以获取特定值

时间:2018-07-12 22:20:08

标签: python

如何检查我的密钥的值是否为<class 'inspect._empty'>

字典看起来像:

{'abc': <class 'inspect._empty'>, 'xyz': None}

现在,我要设置abc等于x值(如果它具有值<class 'inspect._empty'>

    def _arg_unset(args_dict: Dict, key: str) -> bool:
    """return True if key is not set to some actual value in args_dict"""
    return args_dict.get(key) in {None, Parameter.empty}

在上述代码中,dict需要作为第一参数传递,而key作为第二参数传递。

1 个答案:

答案 0 :(得分:2)

>>> import inspect
>>> d = {'abc': inspect._empty, 'xyz': None}
>>> d
{'abc': <class 'inspect._empty'>, 'xyz': None}
>>> {k:v if v != inspect._empty else 'x' for k,v in d.items()}
{'abc': 'x', 'xyz': None}
>>> 
相关问题