How to Use the Python dict() Function

09/17/2021

Contents

In this article, you will learn how to use the Python dict() function.

Python dict() Function

The Python dict() function is used to create a new dictionary object. It can also be used to convert other data types like lists, tuples, and sets into dictionaries. Here are some examples of how to use the dict() function:

Creating a dictionary:

You can create a new empty dictionary by calling the dict() function without any arguments:

my_dict = dict()

You can also create a new dictionary with key-value pairs:

my_dict = dict(a=1, b=2, c=3)

Or with a list of key-value pairs:

my_dict = dict([('a', 1), ('b', 2), ('c', 3)])
Converting other data types into dictionaries:

You can use the dict() function to convert a list of tuples into a dictionary:

my_list = [('a', 1), ('b', 2), ('c', 3)]
my_dict = dict(my_list)

You can also convert a tuple of tuples into a dictionary:

my_tuple = (('a', 1), ('b', 2), ('c', 3))
my_dict = dict(my_tuple)

Or convert two lists into a dictionary:

keys = ['a', 'b', 'c']
values = [1, 2, 3]
my_dict = dict(zip(keys, values))
Updating a dictionary:

You can use the dict() function to update an existing dictionary by passing in a dictionary object or an iterable of key-value pairs:

my_dict = {'a': 1, 'b': 2, 'c': 3}
my_dict.update({'d': 4, 'e': 5})
Accessing values in a dictionary:

You can access the value associated with a key in a dictionary using the square bracket notation:

my_dict = {'a': 1, 'b': 2, 'c': 3}
value_of_a = my_dict['a']
Removing items from a dictionary:

You can remove an item from a dictionary using the del statement or the pop() method:

my_dict = {'a': 1, 'b': 2, 'c': 3}
del my_dict['a']
value_of_a = my_dict.pop('a', None)  # returns None if 'a' is not in the dictionary

These are some of the common use cases of the dict() function in Python.