Open In App

Python dict() Function

Improve
Improve
Like Article
Like
Save
Share
Report

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




# passing keyword arguments to dict() method
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}
  
# deep copy using dict
dict_deep = dict(main_dict)
  
# shallow copy without dict
dict_shallow = main_dict
  
# changing value in shallow copy will change main_dict
dict_shallow['a'] = 10
print("After change in shallow copy, main_dict:", main_dict)
  
# changing value in deep copy won't affect 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




# A list of key value pairs is passed and
# a keyword argument is also passed
myDict = dict([('a', 1), ('b', 2), ('c', 3)], d=4)
  
print(myDict)


Output:

{'a': 1, 'b': 2, 'c': 3, 'd': 4}



Last Updated : 29 Nov, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads