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
1) Creating an empty dictionary using dict() function
To create an empty dictionary, dict() function without augments can be used.
Syntax:
Program:
Output:
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:
Program:
Output:
need an explanation for this answer? contact us directly to get an explanation for this answer