In this tutorial, we will write some example codes to introduce how to iterate throng a python dictionary.
Create a dictionary
website = { "url": "https://www.tutorialexample.com", "name": "Tutorial Example", "article_num": 45, "is_available": True }
The result is:
{'url': 'https://www.tutorialexample.com', 'is_available': True, 'article_num': 45, 'name': 'Tutorial Example'}
From the result, we will find the item order of create and print is different.
Iterate through keys
for key in website: print("{}: {}".format(key, website[key]))
The output is:
url: https://www.tutorialexample.com is_available: True article_num: 45 name: Tutorial Example
Iterate through values
for value in website.values(): print(value)
The output is:
https://www.tutorialexample.com True 45 Tutorial Example
Iterate though keys and values
for key, value in website.items(): print("{}: {}".format(key, value))
The output is:
url: https://www.tutorialexample.com is_available: True article_num: 45 name: Tutorial Example
If you want to sort the dictionary in python, you can read: