Get The Most Affordable Hosting in the World!
Starting at just $1.87/month, Vercaa offers unbeatable pricing for world-class web hosting services.
Fast, reliable, and secure hosting to power your website without breaking the bank. Plus, enjoy a free CDN for faster loading times worldwide!
Get Started Now!Unlike a list, tuple or a string, dictionary data type in Python is not a sequence, as the items do not have a positional index. However, traversing a dictionary is still possible with different techniques.
Example 1
Running a simple for loop over the dictionary object traverses the keys used in it.
It will produce the following output −
10 20 30 40
Example 2
Once we are able to get the key, its associated value can be easily accessed either by using square brackets operator or with get() method.
It will produce the following output −
10 : Ten 20 : Twenty 30 : Thirty 40 : Forty
The items(), keys() and values() methods of dict class return the view objects dict_items, dict_keys and dict_values respectively. These objects are iterators, and hence we can run a for loop over them.
Example 3
The dict_items object is a list of key-value tuples over which a for loop can be run as follows:
It will produce the following output −
(10, 'Ten') (20, 'Twenty') (30, 'Thirty') (40, 'Forty')
Here, "x" is the tuple element from the dict_items iterator. We can further unpack this tuple in two different variables.
Example 4
It will produce the following output −
10 : Ten 20 : Twenty 30 : Thirty 40 : Forty
Example 5
Similarly, the collection of keys in dict_keys object can be iterated over.
Respective Keys and values in dict_keys and dict_values are at same index. In the following example, we have a for loop that runs from 0 to the length of the dict, and use the looping variable as index and print key and its corresponding value.
Example 6
The above two code snippets produce identical output −
10 : Ten 20 : Twenty 30 : Thirty 40 : Forty
The End! should you have any inquiries, we encourage you to reach out to the Vercaa Support Center without hesitation.