Friday, November 15, 2024
Google search engine
HomeLanguagesPython dict() Function

Python dict() Function

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'}

A dictionary is a mutable data structure i.e. the data in the dictionary can be modified. 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.

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}

RELATED ARTICLES

Most Popular

Recent Comments