2011-03-09 26 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