简体   繁体   中英

Why python only printing the last key from dictionary?

I was trying the make a function in python and using a for loop to iterate all keys or values from a dictionary and I was trying to assign a global variable inside the function so I can print the keys outside the function but it was only printing the last key:

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()

It only prints the last key because your print() call is outside of the for loop that iterates over the keys. By the time the program gets to your uncommented print() , the value of key is the final value it was assigned inside the loop. To print all values of key , uncomment the print(key) call inside the loop.

Every iteration of the for loop key receives a new value. Once the for loop ended, only the last value of key is assigned to the variable key .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM