The dict() function is a constructor for dictionary objects.

Without any argument, the function returns an empty dictionary.





dict() with key-value pairs

If the function is called with an iterable object containing key-value pairs it creates a dictionary with the elements of the iterable.

items = [(1, 'Python'), (2, 'PHP'), (3, 'Ruby'), (4, 'Java')]

//{1: 'Python', 2: 'PHP', 3: 'Ruby', 4: 'Java'}

In the above example, we have a list of two-length tuples, the dict() function uses the elements of the list to create a dictionary. For each dictionary item, the first element in the tuple is used as key and the second element as the value. 

dict() with another dictionary

The dict() function can also be used to create a new dictionary object from items of another dictionary. The dictionary is passed as the argument and the returned dictionary object contains the same key-value pairs as the other dictionary.


dict1 = {'Nairobi':'Kenya', 'Tokyo':'Japan', 'Delhi':'India'}
dict2 = dict(dict1)
//{'Nairobi': 'Kenya', 'Tokyo': 'Japan', 'Delhi': 'India'}

In the above example, we passed dict1 as the argument to the dict() function. The resulting dictionary(dict2) is instantiated with all elements of dict1.

dict() with keyword arguments

Lastly, the function can be used with keyword arguments to create a dictionary object. The name of each keyword argument will be the dictionary key, and the value associated with the argument the dictionary value.


dict(a = 1, b = 2, c = 3)
//{'a': 1, 'b': 2, 'c': 3}