Facebook Page Twitter Page LinkedIn Page
× Python Tutorial Python Advanced Python Resources Python Libraries


The Python dict() function (or dict() constructor) is used to create dictionary using an iterable object containing key-value pairs.

Syntax

dict(iterable)

Parameters

iterable Required. iterable with key-value pairs etc.

Example: dict function using iterable with key-value pairs

In the below example, dict() function is used to create a dictionary from an iterable containing key-value pairs.

#using tuple of lists as iterable
#similarly tuple of tuples and tuple of sets can be used
MyTuple = (['name', 'John'], ['age', 25])
MyDict = dict(MyTuple)
print(MyDict)

#using list of tuple as iterable
#similarly list of lists and list of sets can be used
MyList = [('name', 'John'), ('age', 25)]
MyDict = dict(MyList)
print(MyDict)

The output of the above code will be:

{'name': 'John', 'age': 25}
{'name': 'John', 'age': 25}

Using Keyword Arguments:

The above result can also be achieved by using keyword argument.

Syntax

dict(keyword arguments)

Parameters

keyword arguments Required. contain as many keyword argument like key = value, key = value ...etc

Example: dict function using keyword argument

In the below example, dict() function is used to create a dictionary by passing keyword arguments.

MyDict = dict(name='John', age=25)
print(MyDict)

The output of the above code will be:

{'name': 'John', 'age': 25}

❮ Python Built-in Functions