ADVERTISEMENT
ADVERTISEMENT

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 »



ADVERTISEMENT


ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.