Loop through a dictionary in Python

Here, we are going to learn how to Loop through a dictionary, how to print the dictionary keys, values, and pair of key & values in Python?
Submitted by Shivang Yadav, on March 24, 2021

A dictionary contains the pair of the keys & values (represents key : value), a dictionary is created by providing the elements within the curly braces ({}), separated by the commas. 

1) Loop through a dictionary to print the keys only

When we loop through a dictionary, it returns the keys only.

Syntax:

for key in dictionary_name:
    print(key)

Program:

# Python program to loop through a dictionary 
# to print the keys only

# creating the dictionary
dict_a = {'id' : 101, 'name' : 'Amit', 'age': 21}

# printing the dictionary
print("Dictionary \'dict_a\' is...")
print(dict_a)

# printing the keys
print("Dictionary \'dict_a\' keys are...")
for x in dict_a:
    print(x)

Output:

Dictionary 'dict_a' is...
{'id': 101, 'name': 'Amit', 'age': 21}
Dictionary 'dict_a' keys are...
id
name
age

2) Loop through a dictionary to print the values only

To print the values only of a dictionary, we use the values() method. When we loop through a dictionary using the values() method – it returns the values of the dictionary one by one.

Syntax:

for value in dictionary_name.values():
    print(value)

Program:

# Python program to loop through a dictionary 
# to print the values only

# creating the dictionary
dict_a = {'id' : 101, 'name' : 'Amit', 'age': 21}

# printing the dictionary
print("Dictionary \'dict_a\' is...")
print(dict_a)

# printing the values
print("Dictionary \'dict_a\' values are...")
for x in dict_a.values():
    print(x)

Output:

Dictionary 'dict_a' is...
{'name': 'Amit', 'age': 21, 'id': 101}
Dictionary 'dict_a' values are...
Amit
21
101

3) Loop through a dictionary to print the keys & values both

To print the keys and values both of a dictionary, we use the items() method. We loop through a dictionary using the items() method – it returns the key:value pair that can be stored in two different variables and then prints them one by one.

Syntax:

for key,value in dictionary_name.items():
    print(key, value)

Program:

# Python program to loop through a dictionary 
# to print the keys & values only

# creating the dictionary
dict_a = {'id' : 101, 'name' : 'Amit', 'age': 21}

# printing the dictionary
print("Dictionary \'dict_a\' is...")
print(dict_a)

# printing the keys & values
print("Dictionary \'dict_a\' keys & values are...")
for x,y in dict_a.items():
    print(x, ':', y)

Output:

Dictionary 'dict_a' is...
{'id': 101, 'name': 'Amit', 'age': 21}
Dictionary 'dict_a' keys & values are...
id : 101
name : Amit
age : 21

Python Dictionary Programs »



Related Programs




Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.