Dictionaries
In this article we will talk about dictionaries, a much more flexible data type than sets.
{key: value}
Unlike regular sequences, dictionaries are composed of unique keys
. Each unique key corresponds to a value
.
Even though dictionaries themselves are mutable data types (we can add change or remove key-value pairs as we please) , the keys themselves that compose the dictionary must be unique, and of an immutable type (string, number or tuple).
Let's look at an example:
inventory = { 'bananas' : 1.29 , 'apples' : 2.99 , 'papayas' : 1.39 }
Above is an example of an inventory dictionary. Dictionaries are denoted by curly braces { }
and as mentioned previously, hold a sequence of key-value pairs. In this case, our keys are the fruits, and our values are the prices.
How do we access a dictionary?
In order to access elements in a dictionary, we must make use of the keys:
print(inventory['bananas'])
>> 1.29
In order to access a certain value in your dictionary, all you have to do is specify which key you would like to access. In our case, we chose bananas
and the value we got was 1.29
Dictionaries are mutable
Dictionaries are mutable. This means that we can add, remove and modify certain elements within the dictionary.
Let's increase the price of our bananas:
inventory['bananas'] = 2.99
print(inventory['bananas'])
>> 2.99
In order to modify a certain element in a dictionary, you start off by accessing it using the key. In our case this was bananas
, and using the equal operator =
you can set the price of the bananas.
The get
method
Dictionaries also have a useful built-in get
method which looks up values using a specified key. If the key you specified doesn't exist, then it would just return None
.
bananas_price = inventory.get('bananas')
print(bananas_price)
>> 2.99
Otherwise, if I put a non existing key, let's say strawberry
strawberries_price = inventory.get('strawberries')
print(strawberries_price)
>> None
Using the in
operator
We can also check if an element is inside a dictionary using the in
operator, which returns a boolean depending on the result.
print('papayas' in inventory)
>> True
If we try out a key that isn't available:
print('celery' in inventory)
>> False