119
Python dict() Function
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.
Signature
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.
Let’s see some examples of dict() function to understand it’s functionality.
Python dict() Function Example 1
A simple example to create an empty or non-empty dictionary. Arguments of the dictionary are optional.
Output:
{} {'a': 1, 'b': 2}
Python dict() Function Example 2
Output:
{'x': 5, 'z': 20, 'y': 10} {'x': 5, 'z': 20, 'y': 10}
Python dict() Function Example 3
Output:
{1: 'One', 2: 'Two', 3: 'Three'} {'y': 'Y', 'x': 'X'}
Next TopicPython Functions