Loop through a Dictionary in Python
Dictionary is a collection of key: values pairs and is used to store data in python. It is an unordered collection of different sets of data, for example, a dictionary can be used to store keys: values pairs of integers, strings, lists, and we can also create a nested dictionary too.
NOTE- With the release of the new version of Python 3.7, the dictionary has been modified and is now an Ordered collection.
Dictionary is mutable which means we can modify, change and update the data inside it. Some functions allow modifications and accession of dictionary:
- keys() – function for returning the keys.
- values() – function for returning the values.
- items() – function for returning the list with all keys and values.
Dictionary also has an indexed property which means we can use the index value to access the data from it. Dictionary’s keys are immutable and can’t have duplicate values whereas, the Keys: Values can be of different data types and are mutable too.
Using For Loop in Python to loop through a dictionary
We can iterate through a dictionary using the conventional For loop. We know that the dictionary contains a large number of Keys: Values pairs and printing each key: value pair can be time and space-consuming. So we use For loop to print keys and values of the dictionary.
# defining a dictionary myDict = { "Gaurav": "A Coder", "Car": "Ferrari" , "Place": "India", "Age": "22" }
We define a dictionary by assigning a variable name here, we have assigned the “myDict” name to the dictionary. We define a dictionary inside curly {} brackets separated by a comma and a semicolon(:).
Code for returning the keys of a dictionary using For loop:
# defining a dictionary myDict = { "Gaurav": "A Coder", "Car": "Ferrari" , "Place": "India", "Age": "22" } # looping through dictionary by using a for loop. for i in myDict : #this loop will print the keys of myDict dictionary. print(i)
OUTPUT:
Gaurav Car Place Age
However, we can also print the values of the keys using for a loop too. Look at the program given below:
# defining a dictionary myDict = { "Gaurav": "A Coder", "Car": "Ferrari" , "Place": "India", "Age": "22" } for i in myDict : #this loop will print the values of myDict dictionary. print(myDict[i])
OUTPUT:
A Coder Ferrari India 22
Leave a Reply