2011-03-09 25 views
1

這是我的代碼:如何打印正確的事「一」時循環「B」

a ={ 
     'power':'力', 
     'magic':'魔', 
     'skill':'技' 
    } 
b =['power','wwwww'] 
for i in b : 
    #print getattr(a,i) 
    print a[i] or 'default string' 

,並顯示錯誤:

Traceback (most recent call last): 
    File "a.py", line 13, in <module> 
    print a[i] or 'default string' 
KeyError: 'wwwww' 

如何打印正確的事情「A」當環 'b',並顯示在 'A' 不要有它

感謝

回答

7

您可以使用獲得()

默認的字符串,
for i in b: 
    print a.get(i, "default string") 
0
if i in a: 
    st = a[i] 
else: 
    st = "default string" 
print st