A dictionary is a data type in Python that can store data in “key: value” pair format. In other words, if we want to store data in “key: value” pair format in Python, then we can use Python dictionaries for that purpose.
For example, let’s say we want to create a data structure that will store the information whether some numbers are prime numbers or not. We can do so easily using a Python dictionary. We will firstly generate or accept as input a sequence of numbers and then we can check the primality of each number. After that, we can create a dictionary and store the data in key: value pair format where the key is the number and the value is a boolean that indicates whether the number is a prime number.
How to initialize a Python dictionary?
A Python dictionary can be initialized in the following way:
prime_numbers = {2: True, 3: True, 4: False, 5: True}
Here, prime_numbers is a dictionary. An integer number is stored as the key and a boolean value as the value. For example, 3 is a prime number and in the dictionary, it is stored as “3: True”. But, 4 is not a prime number. So, it is stored as “4: False” in the dictionary.
Similarly, we can store other data types also as keys and values. For example,
contact_numbers = {“Alice”: 1234, “Bob”: 5678, “Charlie”: 91011}
Here, a string value is stored as a key and an integer as a value.
How to obtain the values in a dictionary?
As I said, in a Python dictionary data is stored in “key: value” format. We can use this key to obtain the corresponding value from the dictionary. For example,






0 Comments