Python 检查键是否在字典中定义
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19241680/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python check that key is defined in dictionary
提问by user10756
How to check that the key is defined in dictionary in python?
如何检查密钥是否在python的字典中定义?
a={}
...
if 'a contains key b':
a[b] = a[b]+1
else
a[b]=1
采纳答案by Martijn Pieters
Use the in
operator:
使用in
运算符:
if b in a:
Demo:
演示:
>>> a = {'foo': 1, 'bar': 2}
>>> 'foo' in a
True
>>> 'spam' in a
False
You really want to start reading the Python tutorial, the section on dictionariescovers this very subject.
你真的想开始阅读 Python 教程,词典部分涵盖了这个主题。
回答by bruno desthuilliers
Its syntax is if key in dict:
:
它的语法是if key in dict:
:
if "b" in a:
a["b"] += 1
else:
a["b"] = 1
Now you may want to look at collections.defaultdict
and (for the above case) collections.Counter
.
现在您可能想要查看collections.defaultdict
和(对于上述情况)collections.Counter
。
回答by Ishaan
if b in a:
a[b]+=1
else:
a[b]=1
回答by Srinivasreddy Jakkireddy
a = {'foo': 1, 'bar': 2}
if a.has_key('foo'):
a['foo']+=1
else:
a['foo']=1
回答by Ranvijay Sachan
parsedData=[]
dataRow={}
if not any(d['url'] == dataRow['url'] for d in self.parsedData):
self.parsedData.append(dataRow)