Today, we will discuss what are dictionaries and why we need them.
A dictionary is a list that stores data in the form of key and value. In other words, instead of storing elements that all serve one purpose, we can store elements that serve different purposes (which are clear in definition).
A dictionary is defined in this syntax:
dictionary_name= {dictionary_key1:dictionary_value1,dictionary_key2:dictionary_value1,...,dictionary_key N:dictionary_valueN}
Here is an example:
As we can see, when we print out the dictionary, we get the result.
It may not be clear as to why we need dictionaries because this example can be done by using a list that stored John Appleseed's information. But the reason becomes strikingly clear when we use a dictionary to access the ages of different people:
To access different people's ages, we do not use indices, unlike the list and tuple. Instead, we use the key values themselves. For example, to access John Appleseed's age, we use the following syntax:
dictionary["John Appleseed"]
If you wish to change the value of a key, you use the following syntax:
dictionary_name[dictionary_key]=new_value
Note: To add elements, use the following syntax:
dictionary_name[new_key]=new_value
There is one thing to notice. Two different keys can have the same value at the same time, while two different values cannot have the same key. Otherwise, the last repeated key is chosen and other copies are discarded.
Those are the uses of dictionaries.