Dictionary Functions in Python
Dictionary is used to store key: value pairs, and it is one of the essential datatypes. We will explore the built-in methods for dictionaries to optimize dictionary use. Multiple built-in functions exist for adding and removing different kinds of data in the dictionary.
First, let’s see how to add elements to dictionaries.
Adding elements to a Dictionary
In Python Dictionary, the Addition of elements can be done in multiple ways.
The first method is simply using the index and assigning value to it. If the key is non-existent, it will add the key: value pair at the end of our dictionary and if it is already used then the value will be replaced.
And another is using the update() method.
First, let’s see one example of the traditional method.
#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'} """
Adding elements using Update() function
Let’s try to add values with the second point using the update() function.
bestJokers.update({"The Dark Knight": "Heath Ledger"}) print(bestJokers) """ output: {'The original Batman series': 'Cesar Romero', 'Joker(2019)': 'Joaquin Phoenix', 'The Dark Knight': 'Heath Ledger'} """
We can’t give two arguments with the update function.
bestJokers.update({"Batman (1989)": "Jack Nicholson"}, {"Suicide Squad":"Jared Leto"}) print(bestJokers) """ output: --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-16-a7fe9eba8707> in <module> ----> 1 bestJokers.update({"Batman (1989)": "Jack Nicholson"}, {"Suicide Squad":"Jared Leto"}) 2 print(bestJokers) TypeError: update expected at most 1 arguments, got 2 """
But we can add multiple values for sure with one statement.
bestJokers.update({"Batman (1989)": "Jack Nicholson", "Suicide Squad":"Jared Leto"}) print(bestJokers) """ output: {'The original Batman series': 'Cesar Romero', 'Joker(2019)': 'Joaquin Phoenix', 'The Dark Knight': 'Heath Ledger', 'Batman (1989)': 'Jack Nicholson', 'Suicide Squad': 'Jared Leto'}} """
Accessing elements from a Dictionary or a nested dictionary
Accessing Dictionary is an easy task. We can simply use the key inside brackets to access the associated value. For e.g = Dictionary["Tom Cruise"]
We have used this way in lists as well by using an index.
There is another way to access elements, which is using the get() method, Let’s try that!
Using get() method
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 out.
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. Here, we will use the get() method to access the values.
## 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 """
What if we try to access a film by Johnny Depp, 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 """
We can see a Key error here. We can deal with such exceptions using the get method.
Let’s first see how to access any value with get.
# Creating a 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"} } } # accessing a element using get() # method print(Filmography.get("Johnny Depp")) """ output: {2019: 'Waiting for the Barbarians', 2018: {'March': 'Sherlock Gnomes', 'October': 'London Fields'}} """
Let’s try accessing nested value with get() by finding 2018 releases of Johnny Depp.
print(Filmography["Johnny Depp"].get(2018)) """ output: {'March': 'Sherlock Gnomes', 'October': 'London Fields'} """
Let’s go one more level deeper and try to find the October release of Johnny with the get method.
print(Filmography["Johnny Depp"][2018].get("October")) """ output: London Fields """
Successful attempts so far! Right?
Now let’s see how get can help us with key errors. When we try to find a key that is wrong or a key which is non-existent, we will get None
as the output
#the nested value in key is "October" not "october" print(Filmography["Johnny Depp"][2018].get("october")) """ output: None """
Removing Elements from Dictionary
Using del keyword
In Python Dictionary, keys can be deleted by using the del keyword. Using the del keyword, specific values from a dictionary and the whole dictionary can be deleted. Items in a Nested dictionary can also be deleted by using the del keyword and providing a specific nested key and a particular key to be deleted from that nested Dictionary.
Note- del Dict will delete the entire dictionary; hence, printing it after deletion will raise an Error.
# Initial 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("Initial Dictionary: ") print(Filmography) # Deleting a Key value del Filmography["Leo De Caprio"] print("\nDeleting a specific key: ") print(Filmography) # Deleting a Key from # Nested Dictionary del Filmography["Johnny Depp"][2018]["October"] print("\nDeleting a key from Nested Dictionary: ") print(Filmography) """ output: Initial Dictionary: {'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'}}} Deleting a specific key: {'Tom Cruise': {2022: 'Top Gun: Maverick', 2018: 'Mission: Impossible – Fallout', 2017: 'American Made', 2016: 'Jack Reacher: Never Go Back'}, 'Johnny Depp': {2019: 'Waiting for the Barbarians', 2018: {'March': 'Sherlock Gnomes', 'October': 'London Fields'}}} Deleting a key from Nested Dictionary: {'Tom Cruise': {2022: 'Top Gun: Maverick', 2018: 'Mission: Impossible – Fallout', 2017: 'American Made', 2016: 'Jack Reacher: Never Go Back'}, 'Johnny Depp': {2019: 'Waiting for the Barbarians', 2018: {'March': 'Sherlock Gnomes'}}} """
Using pop() method
The popitem() returns and removes the last element (key, value) pair from the dictionary.
# Initial 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"} } } # Deleting an arbitrary key # using popitem() function print("\nDictionary before deletion: ", Filmography) pop_ele = Filmography.popitem() print("\nDictionary after deletion: ", Filmography) print("\nThe arbitrary pair returned is: " + str(pop_ele)) """ output: Dictionary before deletion: {'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'}}} Dictionary after deletion: {'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'}} The arbitrary pair returned is: ('Johnny Depp', {2019: 'Waiting for the Barbarians', 2018: {'March': 'Sherlock Gnomes', 'October': 'London Fields'}}) """
Using clear() method
Using the clear() method will delete all values from a dictionary. Remember, it won’t delete the dictionary; it will delete all values. It is Like deleting all files from a folder rather than deleting the entire folder.
# Creating a Dictionary Dict = {1: 'hey', 'name': 'hello', 3: 'hi'} # Deleting entire Dictionary Dict.clear() print("\nDeleting Entire Dictionary: ") print(Dict) """ output: Deleting Entire Dictionary: {} """
Iterating Over Dictionaries
# Initial Dictionary Dict = { 5 : 'Welcome', 6 : 'To', 7 : 'Co-Learning Lounge', 'A' : {1 : 'hello', 2 : 'hi', 3 : 'namaste'}, 'B' : {1 : 'Hello', 2 : 'bonjour'}} for key in Dict: print(key) print("\n") for key in Dict: print(f"The key is {key} and value is {Dict[key]}") print("\n") for key, value in Dict.items(): print(f"The key is {key} and value is {value}") """ output: 5 6 7 A B The key is 5 and value is Welcome The key is 6 and value is To The key is 7 and value is Co-Learning Lounge The key is A and value is {1: 'hello', 2: 'hi', 3: 'namaste'} The key is B and value is {1: 'hola', 2: 'bonjour'} The key is 5 and value is Welcome The key is 6 and value is To The key is 7 and value is Co-Learning Lounge The key is A and value is {1: 'hello', 2: 'hi', 3: 'namaste'} The key is B and value is {1: 'hola', 2: 'bonjour'} """
Add or Update Dictionary
We can add key: value pair to any dictionary by using the keys in []
and assigning values to it. The values will be added as the last element.
If the key already exists, then the value will be replaced in theolder value.
Also, we can use the update function to update the values.
See the example!
# Initial Dictionary # Initial 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"} } } ## Updating the value through assignment operation Filmography["Johnny Depp"][2019] = "The Professor" print(Filmography) """ output: {'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: 'The Professor', 2018: {'March': 'Sherlock Gnomes', 'October': 'London Fields'}}} """
We can also use the update functions to perform a similar operation.
Let’s try to add the 2017 film “Pirates of the Caribbean: Dead Men Tell No Tales.”
Filmography["Johnny Depp"].update({2017: "Pirates of the Caribbean: Dead Men Tell No Tales"}) print(Filmography) """ output: {'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: 'The Professor', 2018: {'March': 'Sherlock Gnomes', 'October': 'London Fields'}, 2017: 'Pirates of the Caribbean: Dead Men Tell No Tales'}} """
Dictionary Methods
Python has a set of built-in methods that you can use on dictionaries. Let’s see the list of these methods and descriptions.
Method Description
clear(): Removes all the elements from the dictionary
copy(): Returns a copy of the dictionary
fromkeys(): Returns a dictionary with the specified keys and value
get(): Returns the value of the specified key
items(): Returns a list containing a tuple for each key-value pair
keys(): Returns a list containing the dictionary’s keys
pop(): Removes the element with the specified key
popitem(): Removes the last inserted key-value pair
setdefault(): Returns the value of the specified key. If the key does not exist: insert the key, with the specified value
update(): Updates the dictionary with the specified key-value pairs
values(): Returns a list of all the values in the dictionary
These are built-in functions used on dictionaries. We have tried these in the examples, and it is highly recommended to try these in a notebook to understand the distinctions of the results.