Python dict function is a constructor which creates a dictionary. Python dictionary provides three different constructors to a create dictionary.
- If no argument is passed, it creates an empty dictionary.
- If a positional argument is given, a dictionary is created with the same key-value pairs. Otherwise, pass an iterable object.
- If keyword arguments are given, the keyword arguments and their values are added to the dictionary created from the positional argument.
Python dict Function Syntax
It has the following syntax:
Example
dict ([**kwargs])
dict ([mapping, **kwargs])
dict ([iterable, **kwargs])
Parameters
- kwargs : It is a keyword argument.
- mapping : It is another dictionary.
- iterable : It is an iterable object in the form of a key-value pair(s).
Return
It returns a dictionary.
Different Examples for Python dict Function
Let’s explore a few examples of the dict function to grasp its capabilities.
Python dict Function Example 1
An illustrative example for generating either an empty dictionary or a dictionary that contains elements. The parameters of the dictionary are not mandatory.
Example
# Python dict() function example
# Calling function
result = dict() # returns an empty dictionary
result2 = dict(a=1,b=2)
# Displaying result
print(result)
print(result2)
Output:
Output
{}
{'a': 1, 'b': 2}
Python dict Function Example 2
Let’s consider an illustration to showcase the functionality of the Python dict function.
Example
# Python dict() function example
# Calling function
result = dict({'x': 5, 'y': 10}, z=20) # Creating dictionary using mapping
result2 = dict({'x': 5, 'y': 10, 'z':20})
# Displaying result
print(result)
print(result2)
Output:
Output
{'x': 5, 'z': 20, 'y': 10}
{'x': 5, 'z': 20, 'y': 10}
Python dict Function Example 3
Let us consider an example to illustrate the functionality of the Python dict Function.
Example
# Python dict() function example
# Calling function
result = dict([(1, 'One'), [2, 'Two'], [3,'Three']]) # Creating using iterable
result2 = dict([['x','X'],('y','Y')])
# Displaying result
print(result)
print(result2)
Output:
Output
{1: 'One', 2: 'Two', 3: 'Three'}
{'y': 'Y', 'x': 'X'}