![]() |
VOOZH | about |
In Python, the dict() constructor is used to create a dictionary object. A dictionary is a built-in data type that stores data in key-value pairs, similar to a real-life dictionary where each word (the key) has a meaning (the value). The dict() constructor helps you create empty dictionaries or convert other types of data, like lists or tuples, into dictionaries.
Example:
{} <class 'dict'>
{1: 'one', 2: 'two'} <class 'dict'>
{'x': 10, 'y': 20, 'z': 30} <class 'dict'>
dict([iterable],**kwargs)
The dict() constructor is useful for:
Let's go through some examples to understand it better.
This creates an empty dictionary. You can add key-value pairs to this dictionary later, as needed.
{}
Here, we use a list of tuples where each tuple contains a key and a value. The dict() constructor takes this list and turns it into a dictionary.
{1: 'apple', 2: 'banana', 3: 'cherry'}
Another way to create a dictionary is by using keyword arguments. This is an easy way to define a dictionary when you already know the keys and values.
{'name': 'Alice', 'age': 30, 'city': 'New York'}
You can also create nested dictionaries (dictionaries inside dictionaries)
{'student1': {'name': 'John', 'age': 21}, 'student2': {'name': 'Emma', 'age': 22}}