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
Parameter | Required/Optional | Description |
---|---|---|
**kwargs | Optional | None, One or Multiple keyword arguments. |
mapping | Optional | A dictionary object. |
iterable | Optional | An iterable object. Could be a tuple, list, set, etc., or any object that implement __iter__() method. |
Returns
The function returns object of type dict.
Examples
1. 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)
Output
{'a': 1, 'b': 3, 'c': 5}
2. 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)
Output
{'m': 4, 'p': 5, 'a': 1, 'b': 3, 'c': 5}
3. 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)
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)
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
4. dict() – Empty Dictionary
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)
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.