Creating a new dictionary in Python
Categories:
Mastering Python Dictionaries: Creation and Initialization

Learn the fundamental methods for creating and initializing dictionaries in Python, from empty dictionaries to complex nested structures.
Dictionaries are one of Python's most powerful and versatile built-in data structures. They allow you to store data in key-value pairs, providing an efficient way to retrieve, add, and modify data. Understanding how to create and initialize dictionaries is a foundational skill for any Python developer. This article will guide you through various techniques, from the simplest empty dictionary to more advanced initialization methods.
Basic Dictionary Creation
The most straightforward way to create a dictionary is by using curly braces {}
. You can either create an empty dictionary and add elements later, or initialize it with key-value pairs directly. Keys must be unique and immutable (e.g., strings, numbers, tuples), while values can be of any data type.
# 1. Creating an empty dictionary
empty_dict = {}
print(f"Empty dictionary: {empty_dict}")
# 2. Creating a dictionary with initial key-value pairs
person = {
"name": "Alice",
"age": 30,
"city": "New York"
}
print(f"Person dictionary: {person}")
# 3. Keys can be numbers too
scores = {
1: "Excellent",
2: "Good",
3: "Average"
}
print(f"Scores dictionary: {scores}")
Examples of creating empty and pre-filled dictionaries using curly braces.
Using the dict()
Constructor
Python's built-in dict()
constructor offers several alternative ways to create dictionaries. This is particularly useful when you have data in other formats, such as lists of tuples or keyword arguments.
flowchart TD A[Start] A --> B{Choose Method} B --> C["Empty dict()"] B --> D["dict() with keyword args"] B --> E["dict() with iterable of pairs"] C --> F[result = dict()] D --> G[result = dict(key1=val1, key2=val2)] E --> H[result = dict([(key1, val1), (key2, val2)])] F --> I[End] G --> I H --> I
Different pathways for creating dictionaries using the dict()
constructor.
# 1. Creating an empty dictionary using dict() constructor
empty_dict_constructor = dict()
print(f"Empty dict() constructor: {empty_dict_constructor}")
# 2. Using keyword arguments
student = dict(name="Bob", age=22, major="Computer Science")
print(f"Student dictionary (keyword args): {student}")
# 3. From a list of tuples (key-value pairs)
items = [("apple", 1.0), ("banana", 0.5), ("orange", 0.75)]
prices = dict(items)
print(f"Prices dictionary (list of tuples): {prices}")
# 4. From a list of lists (key-value pairs)
more_items = [["red", "#FF0000"], ["green", "#00FF00"]]
colors = dict(more_items)
print(f"Colors dictionary (list of lists): {colors}")
Examples demonstrating various uses of the dict()
constructor.
Dictionary Comprehensions for Dynamic Creation
Dictionary comprehensions provide a concise and efficient way to create dictionaries dynamically from existing iterables. They are similar to list comprehensions but generate key-value pairs. This method is excellent for transforming data or filtering elements into a new dictionary.
# 1. Creating a dictionary from a list, squaring values
numbers = [1, 2, 3, 4, 5]
squared_dict = {num: num**2 for num in numbers}
print(f"Squared dictionary: {squared_dict}")
# 2. Creating a dictionary from two lists (keys and values)
keys = ['a', 'b', 'c']
values = [10, 20, 30]
combined_dict = {k: v for k, v in zip(keys, values)}
print(f"Combined dictionary: {combined_dict}")
# 3. Filtering elements while creating
words = ["apple", "banana", "cherry", "date"]
filtered_dict = {word: len(word) for word in words if len(word) > 5}
print(f"Filtered dictionary: {filtered_dict}")
Examples of dictionary comprehensions for dynamic dictionary creation.
for
loops for creating dictionaries, especially when dealing with large datasets or complex transformations.