Empty Dictionary
What You'll Learn: In this tutorial, you'll discover different ways to create an empty dictionary in Python. A dictionary stores data in key-value pairs, making it easier to organize and retrieve information.
Method 1: Using Empty Curly Braces
You can create an empty dictionary by assigning empty curly braces {} to a variable.
Example Code:
myDict = {}
print(type(myDict))
print(myDict)
Output:
<class 'dict'>
{}
What's Happening Here?
myDict = {}creates an empty dictionary and assigns it to the variablemyDict.
Method 2: Using the dict() Built-in Function
Another way to create an empty dictionary is by using the dict() function without any arguments.
Example Code:
myDict = dict()
print(type(myDict))
print(myDict)
Output:
<class 'dict'>
{}
What's Happening Here?
myDict = dict()creates an empty dictionary using thedict()function.
Try It Yourself: Fun Exercises
- Create Your Own Dictionary:
- Use either method to create an empty dictionary.
- Add your favorite fruits and their colors as key-value pairs.
- Initialize a Dictionary:
- Create an empty dictionary using
{}and then add your favorite books and their authors.
- Create an empty dictionary using
Summary:
In this Python tutorial, we learned two ways to create an empty dictionary: using empty curly braces {} and the dict() function. These methods help you set up a dictionary structure that you can later fill with data. Keep experimenting and have fun with dictionaries in Python!