A dictionary is a mutable data structure i.e. the data in the dictionary can be modified. A dictionary is an indexed data structure i.e. the contents of a dictionary can be accessed by using indexes, here in the dictionary, the key is used as an index. Here, the dict()
function is used to create a new dictionary or convert other iterable objects into a dictionary. In this article, we will learn more about Python dict() function.
Python dict() Syntax
dict(**kwarg)dict(iterable, **kwarg)dict(mapping, **kwarg)
Parameters:
kwargs: It is a keyword argument.terable.
iterable: An iterable containing keyword arguments
mapping: It is another dictionary.
dict() Function in Python
dict()
function is used to create a new dictionary or convert other iterable objects into a dictionary. Dictionaries in Python are collections of key-value pairs, and the dict()
function allows us to create them in various ways.
Python dict() Function is used to create a Python dictionary, a collection of key-value pairs.
Python3
dict (One = "1" , Two = "2" )
|
Output:
{'One': '1', 'Two': '2'}
Example 1: Creating dictionary using keyword arguments
We can pass keyword arguments as a parameter with the required values that will be keys and values of the dictionary.
Syntax:
dict(**kwarg)
Python3
myDict = dict (a = 1 , b = 2 , c = 3 , d = 4 )
print (myDict)
|
Output:
{'a': 1, 'b': 2, 'c': 3, 'd': 4}
Example 2: Creating deep-copy of the dictionary using dict()
Creating a new instance (deep copy) of dictionary using dict().
Syntax:
dict(mapping)
Python3
main_dict = { 'a' : 1 , 'b' : 2 , 'c' : 3 }
dict_deep = dict (main_dict)
dict_shallow = main_dict
dict_shallow[ 'a' ] = 10
print ( "After change in shallow copy, main_dict:" , main_dict)
dict_deep[ 'b' ] = 20
print ( "After change in deep copy, main_dict:" , main_dict)
|
Output:
After change in shallow copy, main_dict: {'a': 10, 'b': 2, 'c': 3}
After change in deep copy, main_dict: {'a': 10, 'b': 2, 'c': 3}
Example 3: Creating dictionary using iterables
The keys and values can be passed to dict() in form of iterables like lists or tuples to form a dictionary and keyword arguments can also be passed to dict().
Syntax:
dict(iterable, **kwarg)
Python3
myDict = dict ([( 'a' , 1 ), ( 'b' , 2 ), ( 'c' , 3 )], d = 4 )
print (myDict)
|
Output:
{'a': 1, 'b': 2, 'c': 3, 'd': 4}
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
29 Nov, 2023
Like Article
Save Article