Operations on Dictionary Datatype in Python

Like Lists, We can perform several operations on a dictionary just as adding and accessing elements.

In this blog, we will explore such operations with easy examples.

First, let us start with adding the elements to any dictionary!

Adding elements to a Dictionary

In Python Dictionary, the Addition of elements can be done by accessing the index (key) and assigning value to it. The key: value pair will be added at the end.

Let’s try adding in one empty dictionary!

#Let's create one empty dictionary to store data

bestJokers = {}

 

Let’s add values using the first point (adding one value at a time using the index).

bestJokers["The original Batman series"] = "Cesar Romero"
bestJokers["Joker(2019)"] = "Joaquin"

print(bestJokers)

"""
output:

{'The original Batman series': 'Cesar Romero', 'Joker(2019)': 'Joaquin Phoenix'}

"""

If we use the existing key to assign a new value, the order value will be replaced. Let’s try ‘Joker(2019)’.

bestJokers["Joker(2019)"] = "Joaquin Phoenix"

print(bestJokers)

"""
output:

{'The original Batman series': 'Cesar Romero', 'Joker(2019)': 'Joaquin Phoenix'}

"""

See how the older value got replaced. If we use a different key then Key: Value will be added at the end of the dictionary.

Accessing elements from a Dictionary

To access the items of a dictionary, refer to its key name. Key can be used inside square brackets.

Let’s get to the bottom of it.

In Lists, the index is the address of any particular value, while in Dictionary, its key is the address of the value.

Let’s create one dictionary and break down the index once with visuals.

First, we see one list in the following picture:

The above list has five values; if we have to access any values, we can check with the index (which is the address of any value).

Let’s see a dictionary now with the same values!

In the dictionary, keys act as an index of values. So if we have to access any values, unlike List, we use the keys to find it.

As a bonus, keys also gave context to our values. (In the list, we could only see some names but didn’t know what these names were for, but in the dictionary, the keys tell us about the inventions/discoveries and people associated with those) 🙂

Let’s try accessing the same list and dictionary.

List = ["Newton",	"Marconi",	"Wright",	"Karl Diesel",	"C.V Raman"]

#Let's try to access Sir C.V Raman here (index 4)

List[4]

"""
output:

'C.V Raman'

"""

Let’s now try to access the same value in our dictionary.

Dictionary = {
    "Gravity"       :	"Newton",
    "Radio"         :	"Marconi",
    "Airplane"      :	"Wright",
    "Diesel Engine" :	"Karl Diesel",
    "Raman Effect"	: "C.V Raman"
}

#Let's try access Sir C.V Raman from the dictionary

Dictionary["Raman Effect"]

"""
output:

'C.V Raman'

"""

Easy, right? In dictionaries, keys are our index to find values.

Accessing an element of a nested dictionary

To access the value of any key in the nested dictionary, use indexing [ ] syntax.

It functions the same way we have used it before for other nested datatypes.

## Accessing the nested dictionary

Filmography = {
          "Tom Cruise"  :    { 2022 : "Top Gun: Maverick",
                               2018 : "Mission: Impossible – Fallout",
                               2017 : "American Made",
                               2016 : "Jack Reacher: Never Go Back" },
               
        "Leo De Caprio" :    { 2021 : "Don't Look Up",
                               2019 : "Once Upon a Time in Hollywood" },
               
         "Johnny Depp"  :    { 2019: "Waiting for the Barbarians",
                               2018 : { "March"  : "Sherlock Gnomes",
                                        "October": "London Fields"}
                                                                    }    
               }

print(Filmography["Leo De Caprio"])
print(Filmography["Johnny Depp"])
print(Filmography["Johnny Depp"][2019])
print(Filmography["Johnny Depp"][2018]["October"])

"""
output:

{2021: "Don't Look Up", 2019: 'Once Upon a Time in Hollywood'}
{2019: 'Waiting for the Barbarians', 2018: {'March': 'Sherlock Gnomes', 'October': 'London Fields'}}
Waiting for the Barbarians
London Fields

"""

It will throw a key error if we use the wrong capitalization because keys, as shared above, are case-sensitive.

Let’s try to access the March 2018 release of Johnny Depp.

#Using "march" instead of "March" to access the value

print(Filmography["Johnny Depp"][2018]["march"])

"""
output:

---------------------------------------------------------------------------

KeyError                                  Traceback (most recent call last)

<ipython-input-4-e3a62e03e3cf> in <module>
----> 1 print(Filmography["Johnny Depp"][2018]["march"])


KeyError: 'march'

"""

The key name should be as it is in the dictionary. However, we can access the value even with variables.

Let’s again try to access the march release of Johnny.

month = "March"
year = 2018

print(Filmography["Johnny Depp"][year][month])

"""
output:

Sherlock Gnomes

"""

What if we try to access a film by Johnny Depp, which was released in 2017? (not existing in our data)

Let’s try!

print(Filmography["Johnny Depp"][2017])

"""
output:

---------------------------------------------------------------------------

KeyError                                  Traceback (most recent call last)

<ipython-input-10-d40801d544ca> in <module>
----> 1 print(Filmography["Johnny Depp"][2017])


KeyError: 2017

"""

It will throw a key error if the key is wrong or non-existent.

We have covered all major operations on dictionary datatype. These operations must be easy to understand as these follow the same approach and are relatable because of somewhat similar working as on a List.

There are also some built-in functions to achieve similar tasks. We will explore those in the next blogs. 🙂