在Python中,您可以使用in
运算符来检查字典中是否存在键。
test.py
def main():
fruits = {
'apple':1,
'orange':2,
'banana':3
}
#if key 'apple' exists in fruits?
if 'apple' in fruits:
print(fruits['apple'])
if __name__ == '__main__':
main()
输出量
1
PS已通过Python 3.4.3测试
注意
has_key()
赞成键已被弃用in
d。
参考文献
翻译自: https://mkyong.com/python/python-check-if-key-exists-in-dictionary/