Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to create an empty dictionary in Python?
A dictionary is a fundamental data structure in Python that stores data as key-value pairs. Dictionaries are also known as associative arrays and are represented by curly braces {}. Unlike lists that use numeric indexes, dictionaries use unique keys to access their values.
Keys must be immutable objects like strings, numbers, or tuples, while values can be of any data type. Python provides two simple methods to create an empty dictionary.
Using Curly Braces {}
The most common way to create an empty dictionary is using empty curly braces.
Syntax
variable_name = {}
Where:
variable_name is the name of the dictionary
{} creates an empty dictionary
Example
Here's how to create an empty dictionary using curly braces ?
dict1 = {}
print("The dictionary created using curly braces:", dict1)
print("Type:", type(dict1))
The dictionary created using curly braces: {}
Type: <class 'dict'>
Adding Values to Empty Dictionary
You can add key-value pairs to an empty dictionary using square bracket notation ?
dict1 = {}
print("Empty dictionary:", dict1)
dict1['name'] = 'Alice'
dict1['age'] = 25
print("After adding values:", dict1)
Empty dictionary: {}
After adding values: {'name': 'Alice', 'age': 25}
Using the dict() Function
The dict() constructor creates an empty dictionary when called without arguments.
Syntax
variable_name = dict()
Where:
variable_name is the name of the dictionary
dict() is the constructor function
Example
Creating an empty dictionary using the dict() function ?
dict1 = dict()
print("The dictionary created is:", dict1)
print("Type:", type(dict1))
The dictionary created is: {}
Type: <class 'dict'>
Adding Multiple Values
You can add different types of values to your empty dictionary ?
dict1 = dict()
print("Empty dictionary:", dict1)
dict1['colors'] = ["Blue", "Green", "Red"]
dict1['numbers'] = [1, 2, 3, 4, 5]
dict1['active'] = True
print("After adding values:", dict1)
Empty dictionary: {}
After adding values: {'colors': ['Blue', 'Green', 'Red'], 'numbers': [1, 2, 3, 4, 5], 'active': True}
Comparison
| Method | Syntax | Performance | Best For |
|---|---|---|---|
{} |
Shorter | Slightly faster | Most common usage |
dict() |
More explicit | Function call overhead | Code readability |
Conclusion
Both {} and dict() create empty dictionaries effectively. Use {} for its simplicity and slight performance advantage, or dict() when you want more explicit code.
