Print all key-value pairs in a Dictionary in Python

avatar

Borislav Hadzhiev

Last updated: Sep 16, 2022

banner

Photo from Unsplash

Print all key-value pairs in a Dictionary in Python #

To print all key-value pairs in a dictionary:

  1. Use the dict.items() method to get a view of the dictionary's items.
  2. Use a for loop to iterate over the view.
  3. Use the print() function to print each key-value pair.
main.py
my_dict = { 'name': 'bobbyhadz', 'age': 30, 'language': 'Python' } for key, value in my_dict.items(): # name bobbyhadz # age 30 # language Python print(key, value) print(list(my_dict.keys())) # 👉️ ['name', 'age', 'language'] print(list(my_dict.values())) # 👉️ ['bobbyhadz', 30, 'Python']

The dict.items method returns a new view of the dictionary's items ((key, value) pairs).

main.py
# 👇️ [('name', 'bobbyhadz'), ('age', 30), ('language', 'Python')] print(list(my_dict.items()))

If you need to format the keys and values in any way, use a formatted string literal.

main.py
my_dict = { 'name': 'bobbyhadz', 'age': 30, 'language': 'Python' } for key, value in my_dict.items(): # name=bobbyhadz # age=30 # language=Python print(f'{key}={value}')
Formatted string literals (f-strings) let us include expressions inside of a string by prefixing the string with f.
main.py
var1 = 'bobby' var2 = 'hadz' result = f'{var1}{var2}' print(result) # 👉️ bobbyhadz

Make sure to wrap expressions in curly braces - {expression}.

You can use the dict.keys() and dict.values() methods to print the dictionary's keys and values.

main.py
my_dict = { 'name': 'bobbyhadz', 'age': 30, 'language': 'Python' } print(list(my_dict.keys())) # 👉️ ['name', 'age', 'language'] print(list(my_dict.values())) # 👉️ ['bobbyhadz', 30, 'Python']

The dict.keys method returns a new view of the dictionary's keys.

The dict.values method returns a new view of the dictionary's values.

If you need to join the key-value pairs of the dictionary into a string, use the str.join() method.
main.py
my_dict = { 'name': 'bobbyhadz', 'age': 30, 'language': 'Python' } result = ', '.join(f'{key}: {value}' for key, value in my_dict.items()) # 👇️ name: bobbyhadz, age: 30, language: Python print(result)

We passed a generator expression to the str.join() method.

Generator expressions are used to perform some operation for every element or select a subset of elements that meet a condition.

On each iteration, we use a formatted string literal to format the key-value pair.

The str.join method takes an iterable as an argument and returns a string which is the concatenation of the strings in the iterable.

The string the method is called on is used as the separator between the elements.

We used a comma and a space as the separator between the key-value pairs, but you can use any other delimiter.

Here is an example that uses a newline (\n) character as the separator.

main.py
my_dict = { 'name': 'bobbyhadz', 'age': 30, 'language': 'Python' } result = '\n'.join(f'{key}: {value}' for key, value in my_dict.items()) # name: bobbyhadz # age: 30 # language: Python print(result)

The key-value pairs of the dictionary are printed on separated lines when joined with a newline (\n) character separator.

You can also use the iterable * unpacking operator and the sep argument to print all key-value pairs in a dictionary.

main.py
my_dict = { 'name': 'bobbyhadz', 'age': 30, 'language': 'Python' } # ('name', 'bobbyhadz') # ('age', 30) # ('language', 'Python') print(*my_dict.items(), sep='\n')

The * iterable unpacking operator enables us to unpack an iterable in function calls, in comprehensions and in generator expressions.

The sep argument is the separator between the arguments we pass to print().

main.py
print('bobby', 'hadz', sep='') # 👉️ bobbyhadz print('bobby', 'hadz') # 👉️ bobby hadz

By default, the sep argument is set to a space.

You can use the json.dumps() method to pretty print the key-value pairs in a dictionary.

main.py
import json my_dict = { 'name': 'bobbyhadz', 'age': 30, 'language': 'Python' } # { # "name": "bobbyhadz", # "age": 30, # "language": "Python" # } print(json.dumps(my_dict, indent=4))

The json.dumps method converts a Python object to a JSON formatted string.

If indent is set to a non-negative integer, the JSON array elements or object members get pretty-printed with the specified indent level.

We used an indent level of 4 spaces, but you can use any other positive integer.

You can set the sort_keys argument to True to sort the keys of the dictionary when serializing to JSON.

main.py
import json my_dict = { 'name': 'bobbyhadz', 'age': 30, 'language': 'Python' } # { # "age": 30, # "language": "Python", # "name": "bobbyhadz" # } print(json.dumps(my_dict, indent=4, sort_keys=True))

The sort_keys argument can be used to sort the output alphabetically by key.

You can also use the pprint() method to pretty print the key-value pairs in a dictionary.

main.py
from pprint import pprint my_dict = { 'name': 'bobbyhadz', 'age': 30, 'language': 'Python' } # {'name': 'bobbyhadz', # 'age': 30, # 'language': 'Python'} pprint(my_dict, width=1, sort_dicts=False)

The pprint.pprint method prints the formatted representation of an object.

We set the width argument to 1 to set the desired maximum number of characters per line to 1.

This way, all of the key-value pairs in the dictionary will get printed on separate lines.

We also set the sort_dicts argument to False to prevent the method from sorting the keys in the dictionary alphabetically.

When sort_dicts is set to False, the dictionary's items are printed in insertion order.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.