dict() Constructor in Python
Last Updated :
18 Nov, 2024
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:
Python
a = dict() # creates an empty dictionary
b = dict([(1, 'one'), (2, 'two')]) # converts a list of tuples into a dictionary
c = dict(x=10, y=20, z=30) # creates a dictionary using keyword arguments
print(a, type(a))
print(b, type(b))
print(c, type(c))
Output{} <class 'dict'>
{1: 'one', 2: 'two'} <class 'dict'>
{'x': 10, 'y': 20, 'z': 30} <class 'dict'>
Syntax of dict()
dict([iterable],**kwargs)
- iterable: This is an optional argument. If you pass an iterable (like a list or tuple) of key-value pairs, dict() will convert it into a dictionary.
- kwargs: These are keyword arguments. You can pass keys and values directly as named parameters when creating the dictionary.
- If no arguments are passed, the constructor will return an empty dictionary.
Use of dict() Constructor
The dict() constructor is useful for:
- Creating an empty dictionary that you can fill later.
- Converting other data types (like lists, tuples, and ranges) into dictionaries.
- Creating a dictionary from keyword arguments where you specify the keys and their corresponding values.
Let's go through some examples to understand it better.
Create an Empty Dictionary
This creates an empty dictionary. You can add key-value pairs to this dictionary later, as needed.
Python
empty_dict = dict()
print(empty_dict)
Convert a List of Tuples to a Dictionary
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.
Python
tuple_list = [(1, 'apple'), (2, 'banana'), (3, 'cherry')]
fruit_dict = dict(tuple_list)
print(fruit_dict)
Output{1: 'apple', 2: 'banana', 3: 'cherry'}
Create a Dictionary Using Keyword Arguments
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.
Python
person = dict(name="Alice", age=30, city="New York")
print(person)
Output{'name': 'Alice', 'age': 30, 'city': 'New York'}
Create Nested Dictionaries
You can also create nested dictionaries (dictionaries inside dictionaries)
Python
nested_dict = dict(student1={"name": "John", "age": 21}, student2={"name": "Emma", "age": 22})
print(nested_dict)
Output{'student1': {'name': 'John', 'age': 21}, 'student2': {'name': 'Emma', 'age': 22}}
Similar Reads
Constructors in Python In Python, a constructor is a special method that is called automatically when an object is created from a class. Its main role is to initialize the object by setting up its attributes or state. The method __new__ is the constructor that creates a new instance of the class while __init__ is the init
3 min read
list() constructor in Python In Python list() constructor is a built-in function which construct a list object. We can use list constructor to create an empty list or convert an iterable (dictionary, tuple, string etc.) to a list. Python# Example of list constructor a = list() # creates an empty list b = list((1, 2, 3)) # cover
2 min read
Destructors in Python Constructors in PythonDestructors are called when an object gets destroyed. In Python, destructors are not needed as much as in C++ because Python has a garbage collector that handles memory management automatically. The __del__() method is a known as a destructor method in Python. It is called when
7 min read
Data Abstraction in Python Data abstraction is one of the most essential concepts of Python OOPs which is used to hide irrelevant details from the user and show the details that are relevant to the users. For example, the readers of geeksforgeeks only know that a writer can write an article on geeksforgeeks, and when it gets
5 min read
Decorators in Python In Python, decorators are a powerful and flexible way to modify or extend the behavior of functions or methods, without changing their actual code. A decorator is essentially a function that takes another function as an argument and returns a new function with enhanced functionality. Decorators are
10 min read
Method And Constructor Overloading In Python In object-oriented programming, method, and constructor overloading are powerful features that allow developers to define multiple methods or constructors with the same name but with different parameters. This flexibility enhances code readability, and reusability, and provides a more intuitive inte
4 min read