Python - Loop Dictionaries
Loop Through a Dictionary
You can loop through a dictionary by using a
for
loop.
When looping through a dictionary, the return value are the keys of the dictionary, but there are methods to return the values as well.
ExampleGet your own Python Server
Print all key names in the dictionary, one by one:
for x in thisdict:
print(x)
Try it Yourself »
Example
Print all values in the dictionary, one by one:
for x in thisdict:
print(thisdict[x])
Try it Yourself »
Example
You can also use the values()
method to
return values of a dictionary:
for x in thisdict.values():
print(x)
Try it Yourself »
Example
You can use the keys()
method to
return the keys of a dictionary:
for x in thisdict.keys():
print(x)
Try it Yourself »
Example
Loop through both keys and values, by using the
items()
method:
for x, y in thisdict.items():
print(x, y)
Try it Yourself »
Exercise?What is this?
Test your skills by answering a few questions about the topics of this page
What is a correct syntax for looping through the values of this dictionary:x = {'type' : 'fruit', 'name' : 'apple'}