Course
Loop Dictionaries
Python Tutorial
This Python tutorial has been written for the beginners to help them understand the basic to advanced concepts of Python Programming Language. After completing this tutorial, you will find yourself at a great level of expertise in Python, from where you can take yourself to the next levels to become a world class Software Engineer.
Loop Dictionaries
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.
numbers = {10:"Ten", 20:"Twenty", 30:"Thirty",40:"Forty"}for x in numbers: print (x)
It will produce the following output
10203040
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.numbers = {10:"Ten", 20:"Twenty", 30:"Thirty",40:"Forty"}for x in numbers: print (x,":",numbers[x])
It will produce the following output
10 : Ten20 : Twenty30 : Thirty40 : 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:
numbers = {10:"Ten", 20:"Twenty", 30:"Thirty",40:"Forty"}for x in numbers.items(): print (x)
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
numbers = {10:"Ten", 20:"Twenty", 30:"Thirty",40:"Forty"}for x,y in numbers.items(): print (x,":", y)
It will produce the following output
10 : Ten20 : Twenty30 : Thirty40 : Forty
Example 5
Similarly, the collection of keys in dict_keys object can be iterated over.
numbers = {10:"Ten", 20:"Twenty", 30:"Thirty",40:"Forty"}for x in numbers.keys(): print (x, ":", numbers[x])
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
numbers = {10:"Ten", 20:"Twenty", 30:"Thirty",40:"Forty"}l = len(numbers)for x in range(l): print (list(numbers.keys())[x], ":", list(numbers.values())[x])
The above two code snippets produce identical output
10 : Ten20 : Twenty30 : Thirty40 : Forty
Practice with Online Editor
Note: This Python online Editor is a Python interpreter written in Rust, RustPython may not fully support all Python standard libraries and third-party libraries yet.
Remember to save code(Ctrl
+S
Or
Command
+S
) before run it.