Create a Dictionary in Python
You can create a dictionary using curly braces {}
or the dict()
constructor.
1. Using curly braces {}
You can use {}
to create a dictionary with key-value pairs separated by commas.
For example:
person = {"name": "James", "age": 35, "city": "New York"}
You can also write the above code in multiple lines for better readability, like this:
person = {
"name": "James",
"age": 35,
"city": "New York"
}
You can also create an empty dictionary and add key-value pairs later.
# Create an empty dictionary
person = {}
# Add key-value pairs later
person["name"] = "James"
person["age"] = 35
person["city"] = "New York"
# Print the dictionary
print(person) # Output: {'name': 'James', 'age': 35, 'city': 'New York'}
2. Using dict() constructor
To create a dictionary using the dict()
constructor, you can pass key-value pairs as arguments.
For example:
person = dict(name="James", age=35, city="New York")
You can also create an empty dictionary using the dict()
constructor and add key-value pairs later.
# Create an emtpy dictionary
person = dict()
# Add key-value pairs later
person["name"] = "James"
person["age"] = 35
person["city"] = "New York"
# Print the dictionary
print(person) # Output: {'name': 'James', 'age': 35, 'city': 'New York'}
Creating a dictionary from an iterable of key-value pairs
You can use the dict()
constructor to create a dictionary from an iterable of key-value pairs such as a list of tuples.
For example:
# List of tuples
key_value_pairs = [('a', 1), ('b', 2), ('c', 3)]
# Creating a dictionary from the iterable
my_dict = dict(key_value_pairs)
print(my_dict) # Output: {'a': 1, 'b': 2, 'c': 3}
When to use:
(1) Use {}
when:
- You are manually defining the dictionary with known key-value pairs.
- It is slightly faster than the
dict()
constructor because it doesn’t involve a function call.
(2) Use dict()
constructor when:
- You need to create a dictionary dynamically.
- You need to create a dictionary from an iterable of key-value pairs (e.g., a list of tuples).