The following examples demonstrate How to Create a Dictionary in Python.
Creating an Empty Dictionary
The following example shows creating an empty dictionary.
# programmingempire.com
# Creating an empty Dictionary
my_dict = {}
print("Empty Dictionary: ")
print(my_dict)
Output
Creating a Dictionary Using the dict() Method
In order to create a dictionary with a number of key-value pairs, you can use the dict() method.
# programmingempire.com
# Creating a Dictionary with dict() method
my_dict = dict({221: 'Joe', 872: 'Sam', 473: 'Lui'})
print("\nDictionary with the use of dict(): ")
print(my_dict)
Output
Creating a Dictionary Without Using dict() Method
However, it is also possible to create a dictionary without using the dict() method. The following example demonstrates it.
# programmingempire.com
# Creating a Dictionary without using dict() method
my_dict = {221: 'Joe', 872: 'Sam', 473: 'Lui'}
print("\nDictionary without the use of dict(): ")
print(my_dict)
Output
Creating a Dictionary With Each Item As A Pair
Also, if you wish to create a dictionary by specifying each item as a key-value pair, then use the following syntax.
# programmingempire.com
# Creating a Dictionary with each item as a Pair
my_dict = dict([(67, 'Som'), (489, 'Unn')])
print("\nDictionary with each item as a pair: ")
print(my_dict)
Output
Performing Operations on a Dictionary
Once, a dictionary is created, we can use other operations on it. The following code shows some of these operations. Basically, we can change the value of a key. Also, we can find whether a key is present or not. Furthermore, we can delete an item using its key. Similarly, popitems() removes and returns an item.
# programmingempire.com
# Performing operations on a dictionary
my_dict = {"Luke":76,"Bill":34, "Samy":987}
print(my_dict)
my_dict = {"Tim":1191,"Lee":2390, "Sam":7489,"Bilu":292, "Cherry":7890}
print(my_dict)
my_dict["Bilu"] = 1200
print(my_dict)
my_dict["Cherry"] =[89,95,92,88,94]
print(my_dict)
del my_dict["Lee"]
print(my_dict)
print(len(my_dict))
print("Bilu" in my_dict)
print("Luke" in my_dict)
print("Pink" not in my_dict)
Output
More Operations on Dictionary
The following code shows some more operations. So, we can print all keys. Moreover, we can print keys as a tuple. Also, we can print them as a list. Similarly, we can print values. Likewise, we can print items as key-value pairs. Furthermore, we can perform get and pop operations.
# programmingempire.com
# More operations on a dictionary
my_dict = {"Bill":8591,"Charlie":3490, "Cherry":8489}
print(my_dict)
print(my_dict.keys())
print(tuple(my_dict.keys()))
print(list(my_dict.keys()))
print(my_dict.values())
print(my_dict.items())
print(my_dict.get("Charlie"))
print(my_dict.pop("Charlie"))
print(my_dict)
print(my_dict.popitem())
print(my_dict)
Output
Further Reading
Examples of OpenCV Library in Python
A Brief Introduction of Pandas Library in Python