The Python dict()
is a built-in function that returns a dictionary object or simply creates a dictionary in Python.
Dictionaries are mutable and unordered collections of key-value pairs where keys must be unique and hashable. They are also called associative arrays in other programming languages like php. Read the following article to learn more in detail about Python dictionaries.
Here are the different forms of dict()
constructors.
dict(**kwarg)
dict([mapping, **kwarg])
dict([iterable, **kwarg])
Where,
**kwarg
let you take an arbitrary number of keyword arguments.If no parameters are given in the dict()
function, an empty dictionary is created.
Now let’s go through each type of dict()
constructors we mentioned earlier.
If the keyword argument **kwarg
is empty then an empty dictionary is created. However, If keyword arguments are given, the keyword arguments and their values are added to the dictionary created. If a key to be added is already present, the value from the keyword argument replaces the value from the positional argument.
>>> #creating empty dictionary
>>> dict()
{}
>>> dict(m=8, n=9)
{'m': 8, 'n': 9}
In this case, the dictionary is created with same key-value pairs as mapping object.
>>> dict({'m': 8, 'n': 9})
{'m': 8, 'n': 9}
>>> #passing keyword arguments as well
>>> dict({'m':8, 'n':9}, o=10)
{'m': 8, 'n': 9, 'o': 10}
In this case, each item of the iterable must be iterable with two objects. The first object becomes the key and the following object becomes the value for the corresponding key.
>>> dict([('m', 8), ('n', 9)])
{'m': 8, 'n': 9}
>>> #passing keyword arguments as well
>>> dict([('m', 8), ('n', 9)], o=10)
{'m': 8, 'n': 9, 'o': 10}