Contents
Python – Print Dictionary
To print dictionary items: key:value pairs, keys, or values, you can use an iterator for the corresponding key:value pairs, keys, or values, using dict items() method, dict keys() method, or dict values() method respectively and call print() function.
In this tutorial, we will go through example programs, to print dictionary as a single string, print dictionary key:value pairs individually, print dictionary keys, and print dictionary values.
1. Print Dictionary as a single string
To print whole Dictionary contents, call print() function with dictionary passed as argument. print() converts the dictionary into a single string literal and prints to the standard console output.
In the following program, we shall initialize a dictionary and print the whole dictionary.
Output
{'a': 1, 'b': 2, 'c': 3}
2. Print Dictionary key:value pairs
To print Dictionary key:value pairs, use a for loop to traverse through the key:value pairs, and use print statement to print them. Dictionary items() method returns the iterator for the key:value pairs and returns key, value during each iteration.
In the following program, we shall initialize a dictionary and print the dictionary’s key:value pairs using a Python For Loop.
Python Program
dictionary = {'a': 1, 'b': 2, 'c':3}
for key,value in dictionary.items():
print(key, ':', value)
Run Code CopyOutput
a : 1
b : 2
c : 3
3. Print Dictionary keys
To print Dictionary keys, use a for loop to traverse through the dictionary keys using dictionary keys() method, and call print() function.
In the following program, we shall initialize a dictionary and print the dictionary’s keys using a Python For Loop.
Python Program
dictionary = {'a': 1, 'b': 2, 'c':3}
for key in dictionary.keys():
print(key)
Run Code CopyOutput
a
b
c
4. Print Dictionary values
To print Dictionary values, use a for loop to traverse through the dictionary values using dictionary values() method, and call print() function.
In the following program, we shall initialize a dictionary and print the dictionary’s values using a Python For Loop.
Python Program
dictionary = {'a': 1, 'b': 2, 'c':3}
for value in dictionary.values():
print(value)
Run Code CopyOutput
1
2
3
Summary
In this tutorial, we learned how to print a dictionary using print() built-in function, print the items of dictionary using items() method, print the dictionary keys using keys() method, and print the dictionary values using values() method.