首页 > 解决方案 > 为什么python只打印字典中的最后一个键?

问题描述

我正在尝试在python中创建一个函数并使用for循环来迭代字典中的所有键或值,我试图在函数内部分配一个全局变量,以便我可以在函数外部打印键,但它只是打印最后一个键:

ships = {
'playerShip1' : cv.imread(r'C:\\Users\\a\\Desktop\\desktopFolders\\pyexample\\seafightShip.jpg', cv.IMREAD_UNCHANGED),
'playership2' : cv.imread(r'C:\\Users\\a\\Desktop\\desktopFolders\\pyexample\\seafightCroped.jpg', cv.IMREAD_UNCHANGED)
}

def att():
global key
for key in ships:
    global shipLoc
    shipLoc = key
    #it works okay here     
    #print(key) 

att()
#quit()

#but it only prints the last key here
print(key)
quit()

标签: pythonpython-3.xlistdictionary

解决方案


它只打印最后一个键,因为您的print()调用在for遍历键的循环之外。当程序到达你的 uncommentedprint()时, 的值key是它在循环内分配的最终值。要打印 的所有值key,请取消注释print(key)循环内的调用。


推荐阅读