Python dict()

Python dict() builtin function creates a Python dictionary object from the data given via arguments.

In this tutorial, we will learn about the syntax of Python dict() function, and learn how to use this function with the help of examples.

Syntax

The syntax of dict() function with only keyword arguments as parameter is

dict(**kwargs)

The syntax of dict() function with a mapping (could be another dictionary) and keyword arguments as parameters is

dict(mapping, **kwargs)

The syntax of dict() function with an iterable and keyword arguments as parameters is

dict(iterable, **kwargs)

where

ParameterRequired/OptionalDescription
**kwargsOptionalNone, One or Multiple keyword arguments.
mappingOptionalA dictionary object.
iterableOptionalAn iterable object. Could be a tuple, list, set, etc., or any object that implement __iter__() method.

Returns

The function returns object of type dict.

Example – dict(**kwargs)

In this example, we will give keyword arguments to dict() function.

Python Program

myDictionary = dict(a=1, b=3, c=5)
print(myDictionary)
Try Online

Output

{'a': 1, 'b': 3, 'c': 5}

Example – dict(mapping, **kwargs)

In this example, we will give a dictionary for mapping parameter and keyword arguments to dict() function.

Python Program

mapping = dict(m=4, p=5)
myDictionary = dict(mapping, a=1, b=3, c=5)
print(myDictionary)
Try Online

Output

{'m': 4, 'p': 5, 'a': 1, 'b': 3, 'c': 5}

Example – dict(iterable, **kwargs)

In this example, we will give a list for iterable parameter and keyword arguments to dict() function.

Python Program

iterable = [('m', 4), ('p', 8)]
myDictionary = dict(iterable, a=1, b=3, c=5)
print(myDictionary)
Try Online

Output

{'m': 4, 'p': 8, 'a': 1, 'b': 3, 'c': 5}

If dict() cannot create dictionary from the iterable, the dict() function throws TypeError.

Python Program

iterable = [4, 8]
myDictionary = dict(iterable, a=1, b=3, c=5)
print(myDictionary)
Try Online

Output

Traceback (most recent call last):
  File "d:/workspace/python/example.py", line 2, in <module>
    myDictionary = dict(iterable, a=1, b=3, c=5)
TypeError: cannot convert dictionary update sequence element #0 to a sequence

Example – dict()

In this example, we will not pass any values as arguments to dict() function. dict() returns an empty dictionary.

Python Program

myDictionary = dict()
print(myDictionary)
Try Online

Output

{}

Conclusion

In this Python Tutorial, we have learnt the syntax of Python dict() builtin function, and also learned how to use this function, with the help of Python example programs.