This article covers the use of the Python dict Function.
The python dict function is used to create dictionaries. You can, of course create them manually, but this function allows for greater flexibility and options while creating dictionaries. You may for instance, pass a dictionary into this function, combining it with others to create a larger dictionary.
The dict() function can take three different forms, each of them shown below.
class dict(**kwarg)
class dict(mapping, **kwarg)
class dict(iterable, **kwarg)
**kwarg stands for key word argument. The two ** represent that there may be an arbitrary number of keywords passed. In simpler words, there may be any numbers of keyword arguments from 0 to infinity.
Simply calling the dict() function without any parameters will result in an empty dictionary being produced.
>>> dict()
{}
You can pass keyword arguments such as the ones in below to create a dictionary with specific key value pairs.
>>> dict(a = 1, b = 2)
{'a': 1, 'b': 2}
As mentioned earlier, you can pass pre-existing dictionaries into this function as well. This is called “mapping”.
>>> dict({"a":1, "b":2})
{'a': 1, 'b': 2}
There isn’t much point to simply adding the same dictionary to the dict() function. It is in fact used in combination with additional key value pairs as shown below.
>>> dict({"a":1, "b":2}, c = 3)
{'a': 1, 'b': 2, 'c': 3}
Another interesting feature is the ability to convert iterables into dictionaries. This extends to list and tuples for instance. The condition is that each item in the iterable should have two items in it. The first will take the place of the key and the second will be the value in the key value pair. Basically, nested iterables.
>>> list = [["a",1],["b",2]]
>>> dict(list)
{'a': 1, 'b': 2}
As we did before, we may add in additional key word arguments.
>>> list = [["a",1],["b",2]]
>>> dict(list, c = 3)
{'a': 1, 'b': 2, 'c': 3}
This marks the end of the Python dict() Function article. Any suggestions or contributions for CodersLegacy are more than welcome. Questions can be asked below in the comments section.