Kodeclik Blog
Empty Dictionaries in Python
Dictionaries are a very useful data structure in Python. They are a set of key-value pairs so specific values can be associated with specific keys. For instance, we can have a dictionary of food products in a grocery store (keys) and their prices (values).
An empty dictionary is one where there are no key-value pairs. This usually happens when the dictionary is initially created.
Creating an empty dictionary with {}
The easiest way to create an empty dictionary is as follows.
mydictionary = \{\}
To confirm that this is really an empty dictionary, we can try to find its length:
print("Length of mydictionary is:",len(mydictionary))
The output is:
Length of mydictionary is: 0
You can try to print mydictionary as follows:
print(mydictionary)
This gives:
\{\}
To confirm that mydictionary is really a dictionary, we can try to inspect its type:
print(type(mydictionary))
The output is:
<class 'dict'>
as expected.
Creating an empty dictionary with dict()
A second way to create an empty dictionary is using the dict() constructor without any arguments.
emptydict = dict()
print(emptydict)
The output is:
\{\}
Testing if a dictionary is empty using bool()
Finally, we will find it useful to test if a given dictionary is empty.
A dictionary evaluated in a boolean context returns True if it is not-empty and False otherwise. So to test if a dictionary is empty we can negate this result. Below is a function for this purpose:
def isemptydictionary(d):
return not bool(d)
When we use this function like so:
print(isemptydictionary({}))
print(isemptydictionary({'name': 'John','age': 13}))
we get the expected output:
True
False
Testing if a dictionary is empty without bool()
In fact, we do not really have to use the bool() function. If the dictionary has at least one key, it will evaluate to True and False otherwise. So we can modify the function above as:
def isemptydictionary(d):
return not d
Again trying this function out:
print(isemptydictionary({}))
print(isemptydictionary({'name': 'John','age': 13}))
gives:
True
False
In this blogpost we have learnt about creating and testing for empty dictionaries. Learn more about dictionaries in our posts about length of dictionary, how to check if two dictionaries are equal, and how to initialize a dictionary in Python.
Once you are comfortable with dictionaries, learn how to increment a value in a Python dictionary, and how to find the first key in a Python dictionary.
Interested in more things Python? See our blogpost on Python's enumerate() capability. Also if you like Python+math content, see our blogpost on Magic Squares. Finally, master the Python print function!
Want to learn Python with us? Sign up for 1:1 or small group classes.