2013-10-08 6 views
24

में परिभाषित किया गया है कि कैसे पाइथन में कुंजी में परिभाषित किया गया है?पायथन जांचें कि कुंजी को

if b in a: 

डेमो::

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

आप वास्तव में पढ़ने अजगर ट्यूटोरियल शुरू करना चाहते हैं, section on dictionaries यह बहुत ही विषय को शामिल किया गया

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

उत्तर

78

in ऑपरेटर का प्रयोग करें।

7

इसका वाक्य रचना if key in dict: है:

if "b" in a: 
    a["b"] += 1 
else: 
    a["b"] = 1 

अब आप collections.defaultdict पर और (ऊपर मामले के लिए) collections.Counter देखने के लिए चाहते हो सकता है।

2
a = {'foo': 1, 'bar': 2} 
if a.has_key('foo'): 
    a['foo']+=1 
else: 
    a['foo']=1 
+4

यह 'in' उपयोग करने के लिए, अजगर 3 में नहीं किया जा सकता बेहतर –

1
parsedData=[] 
dataRow={} 
if not any(d['url'] == dataRow['url'] for d in self.parsedData): 
     self.parsedData.append(dataRow) 
संबंधित मुद्दे