Skip to main content

How to create an empty dictionary in Python

How to create an empty dictionary in Python.

Here is a step-by-step tutorial on how to create an empty dictionary in Python:

Step 1: Open your preferred Python development environment or text editor.

Step 2: Begin a new Python script or open an existing one where you want to create the empty dictionary.

Step 3: To create an empty dictionary, you can use the curly braces {} or the built-in dict() function. Let's start by using the curly braces:

my_dict = {}

In this example, we create a new variable called my_dict and assign it an empty dictionary using curly braces.

Step 4: Alternatively, you can use the dict() function to create an empty dictionary:

my_dict = dict()

Here, we use the dict() function to create an empty dictionary and assign it to the variable my_dict.

Step 5: You can also create an empty dictionary and assign values to it later:

my_dict = {}
my_dict['key1'] = 'value1'
my_dict['key2'] = 'value2'

In this example, we create an empty dictionary using curly braces and later assign values to it using key-value pairs.

Step 6: You can verify that your dictionary is empty by using the len() function:

my_dict = {}
print(len(my_dict)) # Output: 0

The len() function returns the number of items in the dictionary. Since the dictionary is empty, it will return 0.

Step 7: Finally, you can access and manipulate the dictionary using various methods and operations available for dictionaries in Python.

my_dict = {}
my_dict['name'] = 'John'
my_dict['age'] = 30

print(my_dict) # Output: {'name': 'John', 'age': 30}

# Accessing values
print(my_dict['name']) # Output: John

# Modifying values
my_dict['age'] = 35
print(my_dict) # Output: {'name': 'John', 'age': 35}

# Removing key-value pairs
del my_dict['name']
print(my_dict) # Output: {'age': 35}

In this example, we assign values to the dictionary, access values using keys, modify values, and remove key-value pairs using the del keyword.

That's it! You have successfully created an empty dictionary in Python and learned how to work with it. Feel free to explore more dictionary operations and methods to enhance your Python programming skills.