Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sockets/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在'中打印正确的内容;a';当循环';b';_Python_Loops - Fatal编程技术网

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