Python检查该键是否在字典中定义 [英] Python check that key is defined in dictionary

查看:105
本文介绍了Python检查该键是否在字典中定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何检查键是否在python中的字典中定义?

How to check that the key is defined in dictionary in python?

a={}
...
if 'a contains key b':
  a[b] = a[b]+1
else
  a[b]=1


推荐答案

使用中的 operator: p>

Use the in operator:

if b in a:

演示:

>>> a = {'foo': 1, 'bar': 2}
>>> 'foo' in a
True
>>> 'spam' in a
False

你真的想开始阅读Python教程, 词典部分涵盖了这个主题。

You really want to start reading the Python tutorial, the section on dictionaries covers this very subject.

这篇关于Python检查该键是否在字典中定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆