Home >Backend Development >Python Tutorial >How to print all key-value pairs in a dictionary in Python
To print all key-value pairs in the dictionary:
Use the dict.items()
method to get a view of the dictionary items.
Use for
to loop through the view.
Use the print()
function to print each key-value pair.
my_dict = { 'name': 'jiyik', 'age': 30, 'language': 'Python' } for key, value in my_dict.items(): # name jiyik # age 30 # language Python print(key, value) print(list(my_dict.keys())) # ????️ ['name', 'age', 'language'] print(list(my_dict.values())) # ????️ ['jiyik', 30, 'Python']
dict.items
Method returns a new view of dictionary items ((key, value) pairs).
# ????️ [('name', 'jiyik'), ('age', 30), ('language', 'Python')] print(list(my_dict.items()))
If we need to format keys and values in any way, use formatted string literals.
my_dict = { 'name': 'jiyik', 'age': 30, 'language': 'Python' } for key, value in my_dict.items(): # name=jiyik # age=30 # language=Python print(f'{key}={value}')
Formatted string literals
f-strings
Let us include an expression in a string by prepending f in front of it.
var1 = 'fql' var2 = 'jiyik' result = f'{var1}{var2}' print(result) # ????️ fqljiyik
Make sure to enclose the expression in braces - {expression}
.
We can use the dict.keys()
and dict.values()
methods to print the keys and values of the dictionary.
my_dict = { 'name': 'jiyik', 'age': 30, 'language': 'Python' } print(list(my_dict.keys())) # ????️ ['name', 'age', 'language'] print(list(my_dict.values())) # ????️ ['jiyik', 30, 'Python']
dict.keys
Method returns a new view of the dictionary keys.
dict.values
Method returns a new view of dictionary values.
If we need to concatenate the key-value pairs of the dictionary into a string, please use the
str.join()
method.
my_dict = { 'name': 'jiyik', 'age': 30, 'language': 'Python' } result = ', '.join(f'{key}: {value}' for key, value in my_dict.items()) # ????️ name: jiyik, age: 30, language: Python print(result)
We pass the generator expression to the str.join()
method.
Generator expressions are used to perform certain operations on each element or to select a subset of elements that meet a condition.
In each iteration, we format the key-value pair using a formatted string literal.
str.join
method takes an iterable object as a parameter and returns a string that is the concatenation of the strings in the iterable object.
The string on which this method is called is used as a separator between elements.
We use commas and spaces as separators between key-value pairs, but you can use any other separator.
The following is an example using the newline character
(\n)
as the delimiter.
my_dict = { 'name': 'jiyik', 'age': 30, 'language': 'Python' } result = '\n'.join(f'{key}: {value}' for key, value in my_dict.items()) # name: jiyik # age: 30 # language: Python print(result)
When concatenated with the newline \n
character delimiter, the dictionary's key-value pairs are printed on separate lines.
We can also use the iterable *
unpacking operator with the sep parameter to print all key-value pairs in the dictionary.
my_dict = { 'name': 'jiyik', 'age': 30, 'language': 'Python' } # ('name', 'jiyik') # ('age', 30) # ('language', 'Python') print(*my_dict.items(), sep='\n')
*
The iterable unpacking operator enables us to unwrap iterable objects in function calls, comprehensions, and generator expressions. The
sep argument is the separator between the arguments we pass to print()
.
print('fql', 'jiyik', sep='') # ????️ fqljiyik print('fql', 'jiyik') # ????️ fql jiyik
By default, the sep parameter is set to spaces.
We can use the json.dumps()
method to pretty print the key-value pairs in the dictionary.
import json my_dict = { 'name': 'jiyik', 'age': 30, 'language': 'Python' } # { # "name": "jiyik", # "age": 30, # "language": "Python" # } print(json.dumps(my_dict, indent=4))
json.dumps
Method converts a Python object into a JSON-formatted string.
If
indent
is set to a non-negative integer, JSON array elements or object members will be pretty-printed using the specified indentation level.
We use an indentation level of 4 spaces, but you can use any other positive integer.
We can set the sort_keys
parameter to True to sort the keys of the dictionary when serializing to JSON.
import json my_dict = { 'name': 'jiyik', 'age': 30, 'language': 'Python' } # { # "age": 30, # "language": "Python", # "name": "jiyik" # } print(json.dumps(my_dict, indent=4, sort_keys=True))
sort_keys
The argument can be used to sort the output alphabetically by keys.
We can also use the pprint()
method to beautifully print the key-value pairs in the dictionary.
from pprint import pprint my_dict = { 'name': 'jiyik', 'age': 30, 'language': 'Python' } # {'name': 'jiyik', # 'age': 30, # 'language': 'Python'} pprint(my_dict, width=1, sort_dicts=False)
pprint.pprint
Method prints the formatted representation of the object.
We set the width parameter to 1 to set the maximum number of characters required per line to 1.
This way, all key-value pairs in the dictionary will be printed on different lines.
We also set the sort_dicts
parameter 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.
The above is the detailed content of How to print all key-value pairs in a dictionary in Python. For more information, please follow other related articles on the PHP Chinese website!