use*_*756 28 python hash dictionary
如何检查密钥是否在python中的字典中定义?
a={}
...
if 'a contains key b':
a[b] = a[b]+1
else
a[b]=1
Run Code Online (Sandbox Code Playgroud)
Mar*_*ers 84
使用in运营商:
if b in a:
Run Code Online (Sandbox Code Playgroud)
演示:
>>> a = {'foo': 1, 'bar': 2}
>>> 'foo' in a
True
>>> 'spam' in a
False
Run Code Online (Sandbox Code Playgroud)
你真的想开始阅读Python教程,关于字典的部分涵盖了这个主题.
它的语法是 if key in dict::
if "b" in a:
a["b"] += 1
else:
a["b"] = 1
Run Code Online (Sandbox Code Playgroud)
现在你可能想看一下collections.defaultdict(对于上面的例子)collections.Counter.