Python built-in Method - dict()

The dict() method is a built-in function in Python that returns a new dictionary object or updates an existing dictionary object from an iterable of key-value pairs.

Here is the syntax for dict() method:

r‮ot refe‬:theitroad.com
dict()
dict(mapping)
dict(iterable)
dict(**kwargs)

where:

  • mapping: a dictionary object or an object that implements the mapping protocol (i.e., has a keys() method that returns an iterable of keys and a __getitem__() method that takes a key and returns a value).
  • iterable: an iterable of key-value pairs, where each item in the iterable is a sequence of two elements, the first element being the key and the second element being the value.
  • **kwargs: key-value pairs that are used to initialize the dictionary.

If no arguments are provided, dict() returns an empty dictionary. If mapping is provided, a new dictionary is created with the same key-value pairs as the mapping object. If iterable is provided, a new dictionary is created with key-value pairs from the iterable. If **kwargs is provided, a new dictionary is created with the key-value pairs specified by the keyword arguments.

Here are some examples of how to use dict():

# create an empty dictionary
d1 = dict()
print(d1)   # {}

# create a dictionary from a mapping object
m = {'a': 1, 'b': 2, 'c': 3}
d2 = dict(m)
print(d2)   # {'a': 1, 'b': 2, 'c': 3}

# create a dictionary from an iterable
it = [('x', 1), ('y', 2), ('z', 3)]
d3 = dict(it)
print(d3)   # {'x': 1, 'y': 2, 'z': 3}

# create a dictionary from keyword arguments
d4 = dict(a=1, b=2, c=3)
print(d4)   # {'a': 1, 'b': 2, 'c': 3}

In the first example, d1 is an empty dictionary. In the second example, d2 is a new dictionary created with the same key-value pairs as the m dictionary. In the third example, d3 is a new dictionary created with key-value pairs from the iterable it. In the fourth example, d4 is a new dictionary created with the key-value pairs specified by the keyword arguments.