Python check that key is defined in dictionary [du

2019-01-23 11:54发布

This question already has an answer here:

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

5条回答
▲ chillily
2楼-- · 2019-01-23 12:03

Use the in operator:

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 dictionaries covers this very subject.

查看更多
Melony?
3楼-- · 2019-01-23 12:12

Its syntax is 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.

查看更多
smile是对你的礼貌
4楼-- · 2019-01-23 12:15
if b in a:
     a[b]+=1
else:
    a[b]=1
查看更多
唯我独甜
5楼-- · 2019-01-23 12:19
a = {'foo': 1, 'bar': 2}
if a.has_key('foo'):
    a['foo']+=1
else:
    a['foo']=1
查看更多
Fickle 薄情
6楼-- · 2019-01-23 12:20
parsedData=[]
dataRow={}
if not any(d['url'] == dataRow['url'] for d in self.parsedData):
       self.parsedData.append(dataRow)
查看更多
登录 后发表回答