How to Create a Dictionary in Python
Learn different ways to create dictionaries in Python for storing key-value pairs.
Dictionaries are Python’s built-in mapping type for storing key-value pairs.
Method 1: Curly Brace Notation
The most common way to create a dictionary:
# Empty dictionary
empty_dict = {}
# Dictionary with items
person = {
"name": "Alice",
"age": 25,
"city": "Paris"
}
print(person["name"]) # Alice
Method 2: dict() Constructor
Create dictionaries using the constructor:
# From keyword arguments
person = dict(name="Alice", age=25, city="Paris")
# From list of tuples
items = [("name", "Bob"), ("age", 30)]
person = dict(items)
print(person) # {'name': 'Bob', 'age': 30}
Method 3: Dictionary Comprehension
Create dictionaries with a concise syntax:
# Squares of numbers
squares = {x: x**2 for x in range(5)}
print(squares) # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
# From two lists
keys = ["a", "b", "c"]
values = [1, 2, 3]
my_dict = {k: v for k, v in zip(keys, values)}
print(my_dict) # {'a': 1, 'b': 2, 'c': 3}
Method 4: fromkeys()
Create a dictionary with default values:
keys = ["name", "age", "city"]
default_dict = dict.fromkeys(keys, "unknown")
print(default_dict) # {'name': 'unknown', 'age': 'unknown', 'city': 'unknown'}
Accessing and Modifying Values
person = {"name": "Alice", "age": 25}
# Access value
print(person["name"]) # Alice
print(person.get("city")) # None (safe access)
print(person.get("city", "N/A")) # N/A (with default)
# Add or update
person["city"] = "Paris"
person["age"] = 26
# Remove
del person["age"]
city = person.pop("city") # Removes and returns value
Useful Methods
person = {"name": "Alice", "age": 25}
# Get all keys
print(person.keys()) # dict_keys(['name', 'age'])
# Get all values
print(person.values()) # dict_values(['Alice', 25])
# Get key-value pairs
print(person.items()) # dict_items([('name', 'Alice'), ('age', 25)])
# Check if key exists
print("name" in person) # True
Summary
- Use
{}for quick dictionary creation - Use
dict()for creating from other structures - Use dictionary comprehensions for transformations
- Use
.get()for safe access with default values