String formatting with a dictionary in Python

avatar

Borislav Hadzhiev

Last updated: Aug 30, 2022

banner

Photo from Unsplash

String formatting with a dictionary in Python #

Use a formatted string literal to perform string formatting with a dictionary, e.g. result = f"Name: {my_dict['name']}, age: {my_dict['age']}". Formatted string literals let us include expressions inside of a string by prefixing the string with f.

main.py
my_dict = {'name': 'Alice', 'age': 30} # ✅ string formatting with dictionary (f-string) result = f"Name: {my_dict['name']}, age: {my_dict['age']}" print(result) # 👉️ Name: Alice, age: 30 # ------------------------------------ # ✅ string formatting with dictionary (str.format()) result = 'Name: {name}, age: {age}'.format(**my_dict) print(result) # 👉️ Name: Alice, age: 30

The first example performs string formatting with a dictionary by using a formatted string literal.

main.py
my_dict = {'name': 'Alice', 'age': 30} result = f"Name: {my_dict['name']}, age: {my_dict['age']}" print(result) # 👉️ Name: Alice, age: 30 result = f'The dict: {my_dict}' print(result) # 👉️ The dict: {'name': 'Alice', 'age': 30}

Make sure to alternate between single and double quotes.

The f-string is wrapped in double quotes, so we used single quotes to access the dictionary's values.

Had we used double quotes, we would have terminated the f-string prematurely.

Formatted string literals (f-strings) let us include expressions inside of a string by prefixing the string with f.

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

You can also use the dict.get() method directly in the f-string.

main.py
my_dict = {} result = f"Name: {my_dict.get('name', 'James Doe')}, age: {my_dict.get('age', 30)}" print(result) # 👉️ Name: James Doe, age: 30
Accessing a key that is not in the dictionary raises a KeyError, but the dict.get() method allows us to specify a default value that is returned if the key is not present.

The dict.get method returns the value for the given key if the key is in the dictionary, otherwise a default value is returned.

The method takes the following 2 parameters:

NameDescription
keyThe key for which to return the value
defaultThe default value to be returned if the provided key is not present in the dictionary (optional)
main.py
my_dict = {'name': 'Alice'} print(my_dict.get('name')) # 👉️ Alice print(my_dict.get('age')) # 👉️ None print(my_dict.get('age', 100)) # 👉️ 100

If a value for the default parameter is not provided, it defaults to None, so the get() method never raises a KeyError.

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

String formatting with a dictionary using str.format() #

Use the str.format() method to perform string formatting with a dictionary, e.g. result = 'Name: {name}, age: {age}'.format(**my_dict). The str.format() method will replace the placeholders with the values in the dictionary.

main.py
my_dict = {'name': 'Alice', 'age': 30} result = 'Name: {name}, age: {age}'.format(**my_dict) print(result) # 👉️ Name: Alice, age: 30

We used the ** syntax to unpack the dictionary into keyword arguments in the call to the str.format() method.

You can imagine that the format() method got called with the following arguments - str.format(name="Alice", age=30).

The str.format method performs string formatting operations.

The string the method is called on can contain replacement fields specified using curly braces {}.

Each replacement field should contain either the numeric index of a position argument or the name of a keyword argument.

main.py
first = 'James' last = 'Doe' result = "His name is {f} {l}".format(f=first, l=last) print(result) # 👉️ "His name is James Doe"

The example above uses keyword arguments. This is what happens under the hood when we use the ** syntax to unpack the dictionary in the call to str.format().

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.