Print each key-value pair of dictionary on a new line in Python

avatar

Borislav Hadzhiev

Last updated: Sep 17, 2022

banner

Photo from Unsplash

Print each key-value pair of dictionary on a new line in Python #

To print each key-value pair of a dictionary on a new 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 object.
  3. Use the print() function to print each key-value pair on a new line.
main.py
my_dict = { 'name': 'Borislav Hadzhiev', 'site': 'bobbyhadz.com', 'id': 1, } # 👇️ using for loop for key, value in my_dict.items(): # name Borislav Hadzhiev # site bobbyhadz.com # id 1 print(key, value) # ------------------------------------------------------ # 👇️ using str.join() result = '\n'.join(f'{key}: {value}' for key, value in my_dict.items()) # name: Borislav Hadzhiev # site: bobbyhadz.com # id: 1 print(result)

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

main.py
my_dict = { 'name': 'Borislav Hadzhiev', 'site': 'bobbyhadz.com', 'id': 1, } # 👇️ dict_items([('name', 'Borislav Hadzhiev'), ('site', 'bobbyhadz.com'), ('id', 1)]) print(my_dict.items())
We used a for loop to iterate over the items view and used the print() function to print each key-value pair on a new line.

By default, the print function's end argument is set to a newline (\n) character, so a new line is added after each call to print().

main.py
print('a', 'b', 'c') # 👉️ 'a b c\n' print('a', 'b', 'c', end='') # 👉️ 'a b c'

If you need to format the key-value pairs in a certain way when printing them, use a formatted string literal.

main.py
my_dict = { 'name': 'Borislav Hadzhiev', 'site': 'bobbyhadz.com', 'id': 1, } for key, value in my_dict.items(): # Key: name, Value: Borislav Hadzhiev # Key: site, Value: bobbyhadz.com # Key: id, Value: 1 print(f'Key: {key}, Value: {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}.

Alternatively, you can use the str.join() method.

Print each key-value pair of dictionary on a new line using str.join() #

To print each key-value pair of a dictionary on a new line:

  1. Format the key-value pairs of the dictionary into strings.
  2. Use the str.join() method to join the strings with a newline (\n) character delimiter.
  3. Use the print() function to print the string of key-value pairs.
main.py
my_dict = { 'name': 'Borislav Hadzhiev', 'site': 'bobbyhadz.com', 'id': 1, } result = '\n'.join(f'{key}: {value}' for key, value in my_dict.items()) # name: Borislav Hadzhiev # site: bobbyhadz.com # id: 1 print(result)

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 separator to print each key-value pair of the dictionary on a new line.

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

Print each key-value pair of dictionary on a new line using json.dumps() #

Use the json.dumps() method to print each key-value pair of a dictionary on a new line, e.g. print(json.dumps(my_dict, indent=4)). When the indent argument is set to 4, each key-value pair of the dictionary will get printed on a new line, indented with 4 spaces.

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

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.