Python program to create a dictionary using dict() function

Here, we are going to learn about the dict() function in Python that is used to create a dictionary, we are writing a Python program to create a dictionary using dict() function in Python?
Submitted by Shivang Yadav, on March 23, 2021

In Python programming language, a dictionary is a collection of an unordered collection of data values in the form of key-value pair.

dict() function

The dict() function is a built-in function in Python, it is used to create a dictionary.

Syntax:

dict(key:value pair1,  key:value pair2, ...)

The function parameters are the pairs of key-values to create the dictionary, if we do not provide any argument, dict() method creates an empty dictionary.

1) Creating an empty dictionary using dict() function

To create an empty dictionary, dict() function without augments can be used.

Syntax:

dictionary_name = dict()

Program:

# Python program to create an empty dictionary

# creating an empty dictionary
dict_a = dict()

# printing the dictionary
print("dict_a :", dict_a)

# printing the length
print("Total elements: ", len(dict_a))

Output:

dict_a : {}
Total elements:  0

2) Creating a dictionary with key-value pairs using dict() function

The dict() function is used to create a dictionary by passing the key-value pairs.

Syntax:

dictionary_name = dict(key=value, key=value,...)

Program:

# Python program to create a dictionary with 
# key-value pairs using dict() function

# creating a dictionary
dict_a = dict(id = 101, name = 'Amit Kumar', Age = 21)

# printing the dictionary
print("dict_a :", dict_a)

# printing the length
print("Total elements: ", len(dict_a))

# printing the key-value pairs
for x, y in dict_a.items():
    print(x, ":", y)

Output:

dict_a : {'Age': 21, 'id': 101, 'name': 'Amit Kumar'}
Total elements:  3
Age : 21
id : 101
name : Amit Kumar

Python Dictionary Programs »



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.