Python dict() Function


The Python dict() is a built-in function that returns a dictionary object or simply creates a dictionary in Python.

python dict() function

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.

Python dict() Syntax

Here are the different forms of dict() constructors.

dict(**kwarg)
dict([mapping, **kwarg])
dict([iterable, **kwarg])

Where,

  • kwarg: It’s a keyword argument and is optional in the function. **kwarg let you take an arbitrary number of keyword arguments.
  • mapping: It is also optional (Another dictionary).
  • iterable: It is also optional. An iterable is the collection of key-value pairs where keys must be unique and immutable.

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.

dict(**kwarg)

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.

Example: Create dictionary using keyword arguments

>>> #creating empty dictionary
>>> dict()
{}

>>> dict(m=8, n=9)
{'m': 8, 'n': 9}

dict([mapping, **kwarg])

In this case, the dictionary is created with same key-value pairs as mapping object.

Example: Create dictionary using mapping

>>> 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}

dict([iterable, **kwarg])

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.

Example: Create dictionary using iterables

>>> 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}