1.檢查字典中是否存在鍵或值
in 和 not in 操作符可以檢查值是否存在于列表中碴犬。也可以利用這些操作符,檢查某個鍵或值是否存在于字典中按傅。在交互式環(huán)境中輸入以下代碼:
>>> spam = {'name': 'Zophie', 'age': 7}
>>> 'name' in spam.keys()
True
>>> 'Zophie' in spam.values()
True
>>> 'color' in spam.keys() False
>>> 'color' not in spam.keys() True
>>> 'color' in spam
False
注:在前面的例子中捉超,'color' in spam 本質(zhì)上是一個簡寫版本。相當于'color' in spam.keys()唯绍。這種情況總是對的:如果想要檢查一個值是否為字典中的鍵拼岳,就可以用關(guān)鍵字 in(或 not in),作用于該字典本身况芒。
2.get()方法
在訪問一個鍵的值之前惜纸,檢查該鍵是否存在于字典中,這很麻煩绝骚。在字典有一個get()方法耐版,它有兩個參數(shù):要取得其值的鍵,以及如果該鍵不存在時压汪,返回的備用值粪牲。在交互式環(huán)境中輸入以下代碼:
>>> picnicItems = {'apples': 5, 'cups': 2}
>>> 'I am bringing ' + str(picnicItems.get('cups', 0)) + ' cups.'
'I am bringing 2 cups.'
>>> 'I am bringing ' + str(picnicItems.get('eggs', 0)) + ' eggs.'
'I am bringing 0 eggs.'
因為 picnicItems 字典中沒有'egg'鍵,get()方法返回的默認值是 0止剖。不使用 get()腺阳,代碼就會產(chǎn)生一個錯誤消息,就像下面的例子:
>>> picnicItems = {'apples': 5, 'cups': 2}
>>> 'I am bringing ' + str(picnicItems['eggs']) + ' eggs.'
Traceback (most recent call last):
File "<pyshell#34>", line 1, in <module>
'I am bringing ' + str(picnicItems['eggs']) + ' eggs.'
KeyError: 'eggs'