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.
To confirm that this is really an empty dictionary, we can try to find its length:
The output is:
You can try to print mydictionary as follows:
This gives:
To confirm that mydictionary is really a dictionary, we can try to inspect its type:
The output is:
as expected.

Creating an empty dictionary with dict()

A second way to create an empty dictionary is using the dict() constructor without any arguments.
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:
When we use this function like so:
we get the expected output:

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:
Again trying this function out:
gives:
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.

Join our mailing list

Subscribe to get updates about our classes, camps, coupons, and more.
  • ABOUT

Copyright @ Kodeclik 2023. All rights reserved.