Python 如何在'中打印正确的内容;a';当循环';b';
这是我的代码:Python 如何在'中打印正确的内容;a';当循环';b';,python,loops,Python,Loops,这是我的代码: 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 <mo
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.py”,第13行,在
打印[i]或“默认字符串”
KeyError:“wwwww”
如何在循环“b”时在“a”中打印正确的内容,并在“a”没有时显示默认字符串
谢谢您可以使用。get()
您可以使用
您可以使用:
您可以使用:
for i in b:
print a.get(i, "default string")
print a[i] if i in a else 'default string'
if i in a:
st = a[i]
else:
st = "default string"
print st