[英]Check key exist in python dict
以下是文件輸出:
apples:20
orange:100
以下是代碼:
d = {}
with open('test1.txt') as f:
for line in f:
if ":" not in line:
continue
key, value = line.strip().split(":", 1)
d[key] = value
for k, v in d.iteritems():
if k == 'apples':
v = v.strip()
if v == 20:
print "Apples are equal to 20"
else:
print "Apples may have greater than or less than 20"
if k == 'orrange':
v = v.strip()
if v == 20:
print "orange are equal to 100"
else:
print "orange may have greater than or less than 100"
在上面的代碼中我寫的是“如果k =='orrange':”,但它實際上是“橙色”的輸出文件。
在這種情況下,我必須在輸出文件中打印orrange鍵。 請幫我。 這該怎么做
使用in
關鍵字。
if 'apples' in d:
if d['apples'] == 20:
print('20 apples')
else:
print('Not 20 apples')
如果你想只在鍵存在的情況下獲取值(如果不存在則避免嘗試獲取它),那么你可以使用字典中的get
函數,傳遞一個可選的默認值作為第二個參數(如果你沒有傳遞它,而是返回None
):
if d.get('apples', 0) == 20:
print('20 apples.')
else:
print('Not 20 apples.')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.