Q:

Python program to create a dictionary using dict() function

belongs to collection: Python Dictionary Programs

0

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, ...)

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python Dictionary Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Python program to create a dictionary from a seque... >>
<< Python program to create an empty dictionary...