The dict()
function in Python is a built-in function that is used to create a new dictionary object. It can be called with no arguments to create an empty dictionary, or it can be called with various arguments to create a dictionary with initial key-value pairs.
Here are some common ways to use the dict()
function:
Creating an empty dictionary:
my_dict = dict()
Creating a dictionary from an iterable of key-value pairs:
pairs = [('a', 1), ('b', 2), ('c', 3)]
my_dict = dict(pairs)
# {'a': 1, 'b': 2, 'c': 3}
Creating a dictionary using keyword arguments:
my_dict = dict(a=1, b=2, c=3)
# {'a': 1, 'b': 2, 'c': 3}
Creating a dictionary from two separate lists of keys and values:
keys = ['a', 'b', 'c']
values = [1, 2, 3]
my_dict = dict(zip(keys, values))
# {'a': 1, 'b': 2, 'c': 3}
The dict()
function is a versatile tool for creating dictionaries in Python, and its usage depends on the specific needs of your program.