Use the format() function to format dictionary print in Python. Its in-built String function is used for the purpose of formatting strings according to the position.
Python Dictionary can also be passed to the format() function as a value to be formatted.
"{key}".format(**dict)
Example format dictionary print in Python
The simple example code key is passed to the {} and the format() function is used to replace the key by its value, respectively. Thus, the Python “**” operator is used to unpack the dictionary.
dict1 = {"a": 100, "b": 200, "c": 300}
res = "{a} {b}".format(**dict1)
print(res)
Output:
Python format dictionary pretty
import json
d = {'a': 2, 'b': {'x': 3, 'y': {'t1': 4, 't2': 5}}}
res = json.dumps(d, sort_keys=True, indent=4)
print(res)
Output:
{
"a": 2,
"b": {
"x": 3,
"y": {
"t1": 4,
"t2": 5
}
}
}
Using f-strings (Python 3.6 and later):
my_dict = {'name': 'Alice', 'age': 30, 'city': 'New York'}
print(f"Name: {my_dict['name']}, Age: {my_dict['age']}, City: {my_dict['city']}")
Using the %
operator (deprecated in Python 3):
my_dict = {'name': 'Alice', 'age': 30, 'city': 'New York'}
print("Name: %s, Age: %d, City: %s" % (my_dict['name'], my_dict['age'], my_dict['city']))
Do comment if you have any doubts or suggestions on this Python dictionary topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.