How to Print a Dictionary in Python: Simple Examples
To print a dictionary in Python, use the
print() function with the dictionary variable inside it. This will display the dictionary's keys and values in a readable format.Syntax
Use the print() function with your dictionary variable to display its contents. The dictionary is enclosed in curly braces {} with key-value pairs separated by colons.
print(dictionary): Prints the whole dictionary.
python
print(my_dict)Example
This example shows how to create a dictionary and print it using the print() function. The output displays the dictionary's keys and values.
python
my_dict = {'name': 'Alice', 'age': 30, 'city': 'New York'}
print(my_dict)Output
{'name': 'Alice', 'age': 30, 'city': 'New York'}
Common Pitfalls
One common mistake is trying to print dictionary keys or values without accessing them properly. Another is expecting the dictionary to print in a sorted order by default, but Python dictionaries preserve insertion order.
Also, printing a dictionary inside a string without converting it can cause errors.
python
my_dict = {'a': 1, 'b': 2}
# Wrong: Trying to print keys without accessing
#print(my_dict['c']) # KeyError because 'c' does not exist
# Right: Print keys safely
print(my_dict.get('c', 'Key not found')) # Prints 'Key not found'
# Wrong: Concatenating dictionary with string
# print("Dict: " + my_dict) # TypeError
# Right: Use comma or f-string
print("Dict:", my_dict)
print(f"Dict: {my_dict}")Output
Key not found
Dict: {'a': 1, 'b': 2}
Dict: {'a': 1, 'b': 2}
Quick Reference
Tips for printing dictionaries in Python:
- Use
print(dictionary)to display the whole dictionary. - Use
dictionary.get(key, default)to safely access values. - Use
f"{dictionary}"orprint(..., dictionary)to include dictionaries in strings. - Dictionaries preserve insertion order in Python 3.7+.
Key Takeaways
Use print(dictionary) to display the entire dictionary easily.
Access dictionary values safely with dictionary.get(key, default) to avoid errors.
Include dictionaries in strings using f-strings or commas, not string concatenation.
Python dictionaries keep the order of items as you add them (Python 3.7+).