Python dict() Function

The dict() function in Python is used to create a dictionary. For example:

x = dict()
print(type(x))

The output would be:

<class 'dict'>

Python dict() Function Syntax

There are total of three ways that we can use dict() function to create dictionary. The first way is, when we need to use keyword argument (named argument) to create a dictionary. Here is the syntax:

dict(**kwarg)

Note - About the kwarg or keyword argument. You can use any number of keyword arguments. Each one must be separated by comma in this way:
key1 = value1, key2 = value2, key3 = value3, ..., keyN = valueN

The second one is, when we need to use another dictionary to create a dictionary. Here is the syntax:

dict([mapping, **kwarg])

Note - Dictionary is a standard mapping type.

And the third one is, when we need to use an iterable object (in the form of key-value pair) to create a dictionary. Here is the syntax:

dict([iterable, **kwarg])

Iterable may be a list or tuple etc.

Python dict() Function Example

Here is a simple example uses dict() function to create dictionary with all the three ways as told in the syntax section:

x = dict(Name = "Wayne", Province = "Ontario", Course = "Computer Science")
print(x)

y = dict(x, University = "University of Waterloo")
print(y)

z = dict([["Day", "Fri"], ["Date", 26], ["Month", "Nov"], ["Year", 2021]])
print(z)

The snapshot given below shows the sample output produced by this program:

python dict function

Python Online Test


« Previous Function Next Function »



Like/Share Us on Facebook 😋