Print the items of a dictionary line by line in Python

avatar

Borislav Hadzhiev

Last updated: Sep 12, 2022

banner

Photo from Unsplash

Print the items of a dictionary line by line in Python #

To print the items of a dictionary line by line:

  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 the dictionary's items line by line.
main.py
my_dict = {'id': 1, 'name': 'bobbyhadz', 'age': 30} for key, value in my_dict.items(): # id 1 # name bobbyhadz # age 30 print(key, value)

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

main.py
my_dict = {'id': 1, 'name': 'BobbyHadz'} print(my_dict.items()) # 👉️ dict_items([('id', 1), ('name', 'BobbyHadz')])

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

main.py
my_dict = {'id': 1, 'name': 'bobbyhadz', 'age': 30} for key, value in my_dict.items(): # id=1 # name=bobbyhadz # age=30 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}.

Print the items of a dictionary line by line using pprint() #

Use the pprint() method to print the items of a dictionary line by line, e.g. pprint.pprint(my_dict, width=1). The pprint() method will print the key-value pairs in the dictionary on separate lines when the width argument is set to a maximum width of 1.

main.py
import pprint my_dict = {'id': 1, 'name': 'bobbyhadz', 'age': 30} # {'id': 1, # 'name': 'bobbyhadz', # 'age': 30} pprint.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.

If you'd rather sort the dictionary's keys, either set sort_dicts to True or remove the argument as it is True by default.

main.py
import pprint my_dict = {'id': 1, 'name': 'bobbyhadz', 'age': 30} # {'age': 30, # 'id': 1, # 'name': 'bobbyhadz'} pprint.pprint(my_dict, width=1, sort_dicts=True)

Alternatively, you can use the json.dumps() method.

Print the items of a dictionary line by line using json.dumps() #

Use the json.dumps() method to print the items of a dictionary line by line, e.g. print(json.dumps(my_dict, indent=4)). When the indent argument is set to 4, all of the key-value pairs in the dictionary will get printed on separate lines, indented with 4 spaces.

main.py
import json my_dict = {'id': 1, 'name': 'bobbyhadz', 'age': 30} # { # "id": 1, # "name": "bobbyhadz", # "age": 30 # } 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 = {'id': 1, 'name': 'bobbyhadz', 'age': 30} # { # "age": 30, # "id": 1, # "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.

If the argument is not specified or is set to False, the dictionary's items get printed in insertion order.

Note that the json.dumps() method can only be used with dictionaries that contain values that can be serialized to JSON.

By default, the JSONEncoder class can convert the following objects and types to JSON.

PythonJSON
dictobject
list, tuplearray
strstring
int, float, int and float derived Enumsnumber
Truetrue
Falsefalse
Nonenull

If the dictionary contains values of any other type, it can't be directly passed to the json.dumps() method.

Print the items of a dictionary line by line using str.join() #

To print the items of a dictionary line by line:

  1. Format the items of the dictionary into strings.
  2. Use the str.join() method to join the strings with a newline character separator.
  3. Use the print() function to print the string.
main.py
my_dict = {'id': 1, 'name': 'bobbyhadz', 'age': 30} result = '\n'.join(f'{key}: {value}' for key, value in my_dict.items()) # id: 1 # name: bobbyhadz # age: 30 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 and value into a string.

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 newline (\n) character as the separator to print the dictionary line by line.

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.