Python dict() Function
Python dict() Function is used to create a Python dictionary. A dictionary is a collection of key-value pairs. A dictionary is a mutable data structure i.e. the data in the dictionary can be modified. In python 3.6 and earlier version dictionary is an unordered collection of key-value pairs but from python 3.7 dictionary is ordered data structure. Dictionary is an indexed data structure i.e. the contents of a dictionary can be accessed by using indexes, here in the dictionary the key is used as an index.
Example 1: Creating dictionary using keyword arguments
We can pass keyword arguments as a parameter with the required values that will be keys and values of the dictionary.
Syntax:
class dict(**kwarg)
Python3
# passing keyword arguments to dict() method myDict = dict (a = 1 , b = 2 , c = 3 , d = 4 ) print (myDict) |
Output:
{'a': 1, 'b': 2, 'c': 3, 'd': 4}
Example 2: Creating dictionary by mapping keys and values
Keys can also be mapped to value using a colon and multiple key-value pairs can be separated by a comma and are passed to dict().
Syntax:
class dict(mapping, **kwarg)
Python3
# passing key-values pairs mapped by colon to dict function myDict = dict ({ 'a' : 1 , 'b' : 2 , 'c' : 3 }) print (myDict) |
Output:
{'a': 1, 'b': 2, 'c': 3}
Example 3: Creating dictionary using iterables
The keys and values can be passed to dict() in form of iterables like lists or tuples to form a dictionary and keyword arguments can also be passed to dict().
Syntax:
class dict(iterable, **kwarg)
Python3
# A list of key value pairs is passesd and # keyword argument is also passed myDict = dict ([( 'a' , 1 ), ( 'b' , 2 ), ( 'c' , 3 )], d = 4 ) print (myDict) |
Output:
{'a': 1, 'b': 2, 'c': 3, 'd': 4}