Python -Loop Dictionaries
Loop Through a Dictionary
You can loop through a dictionary by using afor
loop.
When looping through a dictionary, the return value are thekeys of the dictionary, but there are methods to return thevalues as well.
Example
Print all key names in the dictionary, one by one:
for x in thisdict:
print(x)
Try it Yourself »print(x)
Example
Print allvalues in the dictionary, one by one:
for x in thisdict:
print(thisdict[x])
Try it Yourself »print(thisdict[x])
Example
You can also use thevalues()
method to return values of a dictionary:
for x in thisdict.values():
print(x)
Try it Yourself »print(x)
Example
You can use thekeys()
method to return the keys of a dictionary:
for x in thisdict.keys():
print(x)
Try it Yourself »print(x)
Example
Loop through bothkeys andvalues, by using theitems()
method:
for x, y in thisdict.items():
print(x, y)
Try it Yourself »print(x, y)