The Python dict() function is used to create a dictionary, which is a collection of key-value pairs.
Syntax
dict(**kwarg)
Parameters
**kwarg(optional): It allows you to take an arbitrary number of keyword arguments, where each keyword argument is treated as a key-value pair in the dictionary.
Return value
- If no parameters are provided, it returns an empty dictionary.
- If iterable pairs, keyword arguments, or another mapping object is provided, it returns a dictionary containing the key-value pairs derived from these inputs.
Example 1: Creates am empty dictionary
empty_dict = dict()
print(empty_dict)
print(type(empty_dict))
Output
{}
<class 'dict'>
Example 2: Using Keyword Arguments
sample_dict = dict(A=5, B=6, C=7)
print(sample_dict)
print(type(sample_dict))
Output
{'A': 5, 'B': 6, 'C': 7}
<class 'dict'>
Example 3: Dictionary from an iterable
sample_dict = dict([('A', 5), ('B', 6), ('C', 7)], D=8)
print(sample_dict)
print(type(sample_dict))
Output
{'A': 5, 'B': 6, 'C': 7, 'D': 8}
<class 'dict'>
Example 4: Dictionary from another dictionary
sample_dict = {'A': 5, 'B': 6, 'C': 7}
new_dict = dict(sample_dict)
print(new_dict)
Output
{'A': 5, 'B': 6, 'C': 7}
Ankit Lathiya is a Master of Computer Application by education and Android and Laravel Developer by profession and one of the authors of this blog. He is also expert in JavaScript and Python development.