Dictionary Methods In Python

In this chapter, we will explore Python dictionary methods with examples in an approach to meet your learning goals.

Python Dictionary is like a map that stores key-value pairs as data.

To deal with dictionaries, Python provides a number of built-in functions.

Python Dictionary Methods



Python Dictionary Methods

When it comes to Python dictionary methods, you can apply below sets of built-in Python methods to dictionaries.

MethodsOverview
clear()This function eliminates all items from the dictionary.
copy()This method creates a copy of the dictionary in Python dictionary methods.
fromkeys()This method provides a dictionary containing the specified keys and values.
get()This function provides the value associated with the given key.
items()This function provides a collection that contains the dictionary’s keys.
keys()Provides a collection that includes the dictionary’s keys in Python dictionary methods.
pop()Delete the item with the given key.
popitem()Delete the last added key-value pair.
setdefault()Provide the value of the given key. In the absence of the key, insert it with the given value.
update()In Python dictionaries methods, this function updates the dictionary with key-value pairs given by the user.
values()This function produces a list of all the dictionary values.

Dictionary clear() Method

The clear() method deletes all items from a dictionary.

Syntax

dictionary.clear()

There are no parameters.

Delete all items from the footballer_bio_dict dictionary:

Example: 

footballer_bio_dict = { "full name": "Lionel Andres Messi", "Place of birth": "Rosario, Santa Fe, Argentina", "height": "1.70 m (5 ft 7 in)", "position": "Forward" }footballer_bio_dict.clear()print(footballer_bio_dict)

Take out all items from the footballer1_bio_dict and footballer2_bio_dict dictionary:

Example: 

footballer1_bio_dict = { "full name": "Lionel Andres Messi", "Place of birth": "Rosario, Santa Fe, Argentina", "height": "1.70 m (5 ft 7 in)", "position": "Forward" } footballer2_bio_dict = { "full name": "Cristiano Ronaldo", "Place of birth": "Funchal, Madeira, Portugal", "height": "1.87 m (6 ft 2 in)", "position": "Forward", "first club": "Sporting CP", "world cups": 0 }footballer1_bio_dict.clear() footballer2_bio_dict.clear()print(footballer1_bio_dict) print(footballer2_bio_dict)

Dictionary copy() Method

In Python dictionary methods, copy() method generates a copy of the given dictionary.

Syntax

dictionary.copy()

There are no parameters

Copy the footballer_bio_dict dictionary:

Example: 

footballer_bio_dict = { "full name": "Lionel Andres Messi", "Place of birth": "Rosario, Santa Fe, Argentina", "height": "1.70 m (5 ft 7 in)", "position": "Forward" }mrx = footballer_bio_dict.copy()print(mrx)

Copy the footballer1_bio_dict and footballer2bio_dict dictionary:

Example: 

footballer1_bio_dict = { "full name": "Lionel Andres Messi", "Place of birth": "Rosario, Santa Fe, Argentina", "height": "1.70 m (5 ft 7 in)", "position": "Forward" } footballer2_bio_dict = { "full name": "Cristiano Ronaldo", "Place of birth": "Funchal, Madeira, Portugal", "height": "1.87 m (6 ft 2 in)", "position": "Forward", "first club": "Sporting CP", "world cups": 0 }mrx = footballer1_bio_dict.copy() ample = footballer2_bio_dict.copy()print(mrx) print(ample)

Dictionary fromkeys() Method

By calling the fromkeys() method, you can return a dictionary with the keys and values you specify.

Syntax

dict.fromkeys(keys, value)

Parameter Values

Parameter

Overview

keysIt is mandatory. The keys of the new dictionary are specified by an iterable.
valueA non-essential. This value applies to all keys. No value is set by default

Make a dictionary with six keys, all of which have the value “Data”:

Example: 

mrx = ('First_key', 'Second_key', 'Third_key', 'Fourth_key', 'Fifth_key', 'Sixth_key') ample = "Data"pairs_dict = dict.fromkeys(mrx, ample)print(pairs_dict)

Create a dictionary with four keys that all have the value “NFL Team”:

Example: 

mrx = ('New York Giants', 'Los Angeles Chargers', 'Las Vegas Raiders', 'Miami Dolphins') ample = 'NFL Team'nfl_team_dict = dict.fromkeys(mrx, ample)print(nfl_team_dict)

This example is similar to the one above, but without indicating the value:

Example: 

mrx = ('First_key', 'Second_key', 'Third_key', 'Fourth_key', 'Fifth_key', 'Sixth_key')pairs_dict = dict.fromkeys(mrx)print(pairs_dict)

second example similar to the above, but without declaring the value:

Example: 

mrx = ('New York Giants', 'Los Angeles Chargers', 'Las Vegas Raiders', 'Miami Dolphins')nfl_team_dict = dict.fromkeys(mrx) print(nfl_team_dict)

Dictionary get() Method

By calling the get() method, you can get the value of an item specified by its key.

Syntax

dictionary.get(keyname, value)

Parameter Values

Parameter

Overview

keynameThis is essential. Provide the value from the keyname of the item.
valueA choice. In the absence of a key, a value will be returned. By default, the value is None.

Find the value of the “full name” element:

Example: 

footballer_bio_dict = { "full name": "Lionel Andres Messi", "Place of birth": "Rosario, Santa Fe, Argentina", "height": "1.70 m (5 ft 7 in)", "position": "Forward" } mrx = footballer_bio_dict.get("full name") print(mrx)

Identify the value of the “full name” and “height” elements:

Example: 

footballer_bio_dict = { "full name": "Lionel Andres Messi", "Place of birth": "Rosario, Santa Fe, Argentina", "height": "1.70 m (5 ft 7 in)", "position": "Forward" } mrx = footballer_bio_dict.get("full name") ample = footballer_bio_dict.get("height") print(f"Name: {mrx}") print(f"Height: {ample}")

If an item does not exist, try to return its value:

Example: 

footballer_bio_dict = { "full name": "Cristiano Ronaldo", "Place of birth": "Funchal, Madeira, Portugal", "height": "1.87 m (6 ft 2 in)", "position": "Forward" }mrx = footballer_bio_dict.get("First club", "Sporting CP")print(mrx)

Return the value of the two items if it doesn’t exist:

Example: 

footballer_bio_dict = { "full name": "Cristiano Ronaldo", "Place of birth": "Funchal, Madeira, Portugal", "height": "1.87 m (6 ft 2 in)", "position": "Forward" }mrx = footballer_bio_dict.get("First club", "Sporting CP") ample = footballer_bio_dict.get("World cups", 0)print(f"First club: {mrx}") print(f"World cups: {ample}")

Dictionary items() Method

By calling the items() method, you can get a view object.

A view object includes a list of key-value pairs from the dictionary as tuples.

Syntax

dictionary.items()

There no parameters

If you make any changes to the dictionary, the view object will reflect those changes. For example, see the example below.

Get the key-value pairs from the dictionary:

Example: 

footballer_bio_dict = { "full name": "Lionel Andres Messi", "Place of birth": "Rosario, Santa Fe, Argentina", "height": "1.70 m (5 ft 7 in)", "position": "Forward" }mrx = footballer_bio_dict.items()print(mrx)

Find the key-value pairs from the footballer1_bio_dict and footballer2_bio_dict dictionary:

Example: 

footballer1_bio_dict = { "full name": "Lionel Andres Messi", "Place of birth": "Rosario, Santa Fe, Argentina", "height": "1.70 m (5 ft 7 in)", "position": "Forward" } footballer2_bio_dict = { "full name": "Cristiano Ronaldo", "Place of birth": "Funchal, Madeira, Portugal", "height": "1.87 m (6 ft 2 in)", "position": "Forward" } mrx = footballer1_bio_dict.items() ample = footballer2_bio_dict.items()print(f"Player 1: {mrx}") print(f"Player 2: {ample}")

View objects are updated when dictionary items change their values:

Example: 

footballer_bio_dict = { "full name": "Lionel Andres Messi", "Place of birth": "Rosario, Santa Fe, Argentina", "height": "1.70 m (5 ft 7 in)", "position": "Forward" }mrx = footballer_bio_dict.items()footballer_bio_dict["First club"] = "FC Barcelona"print(mrx)

If the value of dictionary elements alters, view objects are updated:

Example: 

footballer1_bio_dict = { "full name": "Lionel Andres Messi", "Place of birth": "Rosario, Santa Fe, Argentina", "height": "1.70 m (5 ft 7 in)", "position": "Forward" } footballer2_bio_dict = { "full name": "Cristiano Ronaldo", "Place of birth": "Funchal, Madeira, Portugal", "height": "1.87 m (6 ft 2 in)", "position": "Forward" }mrx = footballer1_bio_dict.items() ample = footballer2_bio_dict.items()footballer1_bio_dict["First club"] = "FC Barcelona" footballer1_bio_dict["World cups"] = 1footballer2_bio_dict["First club"] = "Sporting CP" footballer2_bio_dict["World cups"] = 0print(f"Player 1: {mrx}") print(f"Player 2: {ample}")

Dictionary keys() Method

Through the keys() method, you can obtain a view object. As a list, the view object includes the keys of the dictionary.

Any changes made to the dictionary will be reflected in the view object, as shown in the example below.

Syntax

dictionary.keys()

There no parameters

Provide the keys to the footballer_bio_dict dictionary:

Example: 

footballer_bio_dict = { "full name": "Lionel Andres Messi", "Place of birth": "Rosario, Santa Fe, Argentina", "height": "1.70 m (5 ft 7 in)", "position": "Forward" }mrx = footballer_bio_dict.keys()print(mrx)

Return the keys to the footballer1_bio_dict and footballer2_bio_dict dictionary:

Example: 

footballer1_bio_dict = { "full name": "Lionel Andres Messi", "Place of birth": "Rosario, Santa Fe, Argentina", "height": "1.70 m (5 ft 7 in)", "position": "Forward" } footballer2_bio_dict = { "full name": "Cristiano Ronaldo", "Place of birth": "Funchal, Madeira, Portugal", "height": "1.87 m (6 ft 2 in)", "position": "Forward" } mrx = footballer1_bio_dict.keys() ample = footballer2_bio_dict.keys()print(f"Player 1: {mrx}") print(f"Player 2: {ample}")

View objects are also updated when an item is added to the dictionary:

Example: 

footballer_bio_dict = { "full name": "Lionel Andres Messi", "Place of birth": "Rosario, Santa Fe, Argentina", "height": "1.70 m (5 ft 7 in)", "position": "Forward" }mrx = footballer_bio_dict.keys()footballer_bio_dict["First club"] = "FC Barcelona"print(mrx)

When items are added to the dictionaries, the view objects are also updated:

Example: 

footballer1_bio_dict = { "full name": "Lionel Andres Messi", "Place of birth": "Rosario, Santa Fe, Argentina", "height": "1.70 m (5 ft 7 in)", "position": "Forward" } footballer2_bio_dict = { "full name": "Cristiano Ronaldo", "Place of birth": "Funchal, Madeira, Portugal", "height": "1.87 m (6 ft 2 in)", "position": "Forward" }mrx = footballer1_bio_dict.keys() ample = footballer2_bio_dict.keys()footballer1_bio_dict["First club"] = "FC Barcelona" footballer1_bio_dict["World cups"] = 1footballer2_bio_dict["First club"] = "Sporting CP" footballer2_bio_dict["World cups"] = 0print(f"Player 1: {mrx}") print(f"Player 2: {ample}")

Dictionary pop() Method

By calling the pop() method, you can remove an item from a dictionary.

In the example below, the return value of pop() is the value of the deleted item.

Syntax

dictionary.pop(keyname, defaultvalue)

Parameter Values

Parameter

Overview

keynameIt is necessary. This is the keyname of the item you want to delete.
defaultvalueA choice. If the key specified does not exist, this value will be returned.

An error will be raised if this parameter is not specified and no item with the specified key can be found.

Delete the word “position” from the dictionary:

Example: 

footballer_bio_dict = { "full name": "Lionel Andres Messi", "Place of birth": "Rosario, Santa Fe, Argentina", "height": "1.70 m (5 ft 7 in)", "position": "Forward" }footballer_bio_dict.pop("position")print(footballer_bio_dict)

Eliminate the words “height” and “position” from the two dictionaries:

Example: 

footballer1_bio_dict = { "full name": "Lionel Andres Messi", "Place of birth": "Rosario, Santa Fe, Argentina", "height": "1.70 m (5 ft 7 in)", "position": "Forward" } footballer2_bio_dict = { "full name": "Cristiano Ronaldo", "Place of birth": "Funchal, Madeira, Portugal", "height": "1.87 m (6 ft 2 in)", "position": "Forward" } footballer1_bio_dict.pop("height") footballer1_bio_dict.pop("position") footballer2_bio_dict.pop("height") footballer2_bio_dict.pop("position")print(f"Player 1: {footballer1_bio_dict}") print(f"Player 2: {footballer2_bio_dict}")

Pop() method returns the value of the removed item:

Example: 

footballer_bio_dict = { "full name": "Lionel Andres Messi", "Place of birth": "Rosario, Santa Fe, Argentina", "height": "1.70 m (5 ft 7 in)", "position": "Forward" }mrx = footballer_bio_dict.pop("position")print(footballer_bio_dict) print(f"Removed item: {mrx}")

The pop() method gives the value of the items that have been deleted:

Example: 

footballer1_bio_dict = { "full name": "Lionel Andres Messi", "Place of birth": "Rosario, Santa Fe, Argentina", "height": "1.70 m (5 ft 7 in)", "position": "Forward" } footballer2_bio_dict = { "full name": "Cristiano Ronaldo", "Place of birth": "Funchal, Madeira, Portugal", "height": "1.87 m (6 ft 2 in)", "position": "Forward" } mrx1 = footballer1_bio_dict.pop("height") mrx2 = footballer1_bio_dict.pop("position") ample1 = footballer2_bio_dict.pop("height") ample2 = footballer2_bio_dict.pop("position")print(f"Player 1: {footballer1_bio_dict}") print(f"Removed items: {mrx1} and {mrx2}") print(f"Player 2: {footballer2_bio_dict}") print(f"Removed items: {ample1} and {ample2}")

Dictionary popitem() Method

By calling the popitem() method, you can remove the last item added to the dictionary.

Before Python version 3.7, popitem() removes a random item.

See the example below to see what the removed item is, which is a tuple returned by popitem().

Syntax

dictionary.popitem()

There no parameters

From the footballer_bio_dict dictionary, delete the last item:

Example: 

footballer_bio_dict = { "full name": "Lionel Andres Messi", "Place of birth": "Rosario, Santa Fe, Argentina", "height": "1.70 m (5 ft 7 in)", "position": "Forward" }footballer_bio_dict.popitem()print(footballer_bio_dict)

Take out the last item from the footballer1_bio_dict and footballer2_bio_dict Dictionaries:

Example: 

footballer1_bio_dict = { "full name": "Lionel Andres Messi", "Place of birth": "Rosario, Santa Fe, Argentina", "height": "1.70 m (5 ft 7 in)", "position": "Forward" } footballer2_bio_dict = { "full name": "Cristiano Ronaldo", "Place of birth": "Funchal, Madeira, Portugal", "height": "1.87 m (6 ft 2 in)", "position": "Forward" } footballer1_bio_dict.popitem() footballer2_bio_dict.popitem()print(f"Player 1: {footballer1_bio_dict}") print(f"Player 2: {footballer2_bio_dict}")

popitem() method returns the value of the deleted last item:

Example: 

footballer_bio_dict = { "full name": "Lionel Andres Messi", "Place of birth": "Rosario, Santa Fe, Argentina", "height": "1.70 m (5 ft 7 in)", "position": "Forward", "first club": "FC Barcelona" }mrx = footballer_bio_dict.popitem()print(footballer_bio_dict) print(f"Last removed item: {mrx}")

The popitem() method returns the value of the last item that was deleted in both of the dictionaries:

Example: 

footballer1_bio_dict = { "full name": "Lionel Andres Messi", "Place of birth": "Rosario, Santa Fe, Argentina", "height": "1.70 m (5 ft 7 in)", "position": "Forward", "first club": "FC Barcelona", "world cups": 1 } footballer2_bio_dict = { "full name": "Cristiano Ronaldo", "Place of birth": "Funchal, Madeira, Portugal", "height": "1.87 m (6 ft 2 in)", "position": "Forward", "first club": "Sporting CP", "world cups": 0 } mrx = footballer1_bio_dict.popitem() ample = footballer2_bio_dict.popitem()print(f"Player 1: {footballer1_bio_dict}") print(f"Last removed item: {mrx}") print(f"Player 2: {footballer2_bio_dict}") print(f"Last removed item: {ample}")

Dictionary setdefault() Method

In the setdefault() method, the item with the specified key is returned with its default value.

Syntax

dictionary.setdefault(keyname, value)

Parameter Values

Parameter

Overview

keynameThis is essential. You need the keyname of the item you want to return the value for
valueThe optional component.
This parameter has no effect if the key already exists.
This value becomes the key’s value if the key does not exist.
The default value is None.

Insert the key, with the given value, if it does not exist, as shown in the example below.

Find the value of the “first club” item:

Example: 

footballer_bio_dict = { "full name": "Lionel Andres Messi", "Place of birth": "Rosario, Santa Fe, Argentina", "height": "1.70 m (5 ft 7 in)", "position": "Forward", "first club": "FC Barcelona" }mrx = footballer_bio_dict.setdefault("first club","Real Madrid CF")print(mrx)

Identify the value of the “first club”, “height” and “position” items:

Example: 

footballer_bio_dict = { "full name": "Lionel Andres Messi", "Place of birth": "Rosario, Santa Fe, Argentina", "height": "1.70 m (5 ft 7 in)", "position": "Forward", "first club": "FC Barcelona" }mrx1 = footballer_bio_dict.setdefault("first club","Real Madrid CF") mrx2 = footballer_bio_dict.setdefault("height","6 ft 3 in") mrx3 = footballer_bio_dict.setdefault("position","Defender")print(mrx1) print(mrx2) print(mrx3)

Find the value of the “world cups” item; if there is no “world cups” item, insert 1:

Example: 

footballer_bio_dict = { "full name": "Lionel Andres Messi", "Place of birth": "Rosario, Santa Fe, Argentina", "height": "1.70 m (5 ft 7 in)", "position": "Forward", "first club": "FC Barcelona" }mrx = footballer_bio_dict.setdefault("world cups",1)print(footballer_bio_dict) print(f"New default item: {mrx}")

Find the value of the “first club”, “shoe size” and “world cups” item; if there is no “first club” item, insert “FC Barcelona”, if there is no “shoe size” item, insert 10 and last if there is no “world cups” item, insert 1:

Example: 

footballer_bio_dict = { "full name": "Lionel Andres Messi", "Place of birth": "Rosario, Santa Fe, Argentina", "height": "1.70 m (5 ft 7 in)", "position": "Forward" }mrx1 = footballer_bio_dict.setdefault("first club","FC Barcelona") mrx2 = footballer_bio_dict.setdefault("shoe size",10) mrx3 = footballer_bio_dict.setdefault("world cups",1)print(f"New default items:\n{mrx1}\n{mrx2}\n{mrx3}") print(footballer_bio_dict)

Dictionary update() Method

The update() method appends the given elements to the dictionary.

Items can be dictionaries or iterable objects with key-value pairs.

Syntax

dictionary.update(iterable)

Parameter Values

Parameter

Overview

iterableKey-value pairs will be entered into the dictionary via a dictionary or an iterable object.

Add an element to the dictionary:

Example: 

footballer_bio_dict = { "full name": "Lionel Andres Messi", "Place of birth": "Rosario, Santa Fe, Argentina", "height": "1.70 m (5 ft 7 in)", "position": "Forward" }footballer_bio_dict.update({"first club":"FC Barcelona"})print(footballer_bio_dict)

Add three items to the dictionary:

Example: 

footballer_bio_dict = { "full name": "Lionel Andres Messi", "Place of birth": "Rosario, Santa Fe, Argentina", "height": "1.70 m (5 ft 7 in)", "position": "Forward" }footballer_bio_dict.update({"first club":"FC Barcelona", "world cups":1, "shoe size":10})print(footballer_bio_dict)

Python Dictionary Methods – values()

You can return a view object using the values() method in Python dictionary methods.

As a list, the view object contains dictionary values.

Syntax

dictionary.values()

There are no parameters

Any changes made to the dictionary will be reflected in the view object, as shown in the example below.

Provide the values to the footballer_bio_dict dictionary:

Example: 

footballer_bio_dict = { "full name": "Lionel Andres Messi", "Place of birth": "Rosario, Santa Fe, Argentina", "height": "1.70 m (5 ft 7 in)", "position": "Forward" }mrx = footballer_bio_dict.values()print(mrx)

Return the values to the footballer1_bio_dict and footballer2_bio_dict dictionary:

Example: 

footballer1_bio_dict = { "full name": "Lionel Andres Messi", "Place of birth": "Rosario, Santa Fe, Argentina", "height": "1.70 m (5 ft 7 in)", "position": "Forward" } footballer2_bio_dict = { "full name": "Cristiano Ronaldo", "Place of birth": "Funchal, Madeira, Portugal", "height": "1.87 m (6 ft 2 in)", "position": "Forward" } mrx = footballer1_bio_dict.values() ample = footballer2_bio_dict.values()print(f"Player 1: {mrx}") print(f"Player 2: {ample}")

View objects are also updated when an values is added to the dictionary:

Example: 

footballer_bio_dict = { "full name": "Lionel Andres Messi", "Place of birth": "Rosario, Santa Fe, Argentina", "height": "1.70 m (5 ft 7 in)", "position": "Forward" }mrx = footballer_bio_dict.values()footballer_bio_dict["First club"] = "FC Barcelona"print(mrx)

When values are added to the dictionaries, the view objects are also updated:

Example: 

footballer1_bio_dict = { "full name": "Lionel Andres Messi", "Place of birth": "Rosario, Santa Fe, Argentina", "height": "1.70 m (5 ft 7 in)", "position": "Forward" } footballer2_bio_dict = { "full name": "Cristiano Ronaldo", "Place of birth": "Funchal, Madeira, Portugal", "height": "1.87 m (6 ft 2 in)", "position": "Forward" }mrx = footballer1_bio_dict.values() ample = footballer2_bio_dict.values()footballer1_bio_dict["First club"] = "FC Barcelona" footballer1_bio_dict["World cups"] = 1footballer2_bio_dict["First club"] = "Sporting CP" footballer2_bio_dict["World cups"] = 0print(f"Player 1: {mrx}") print(f"Player 2: {ample}")

Python Dictionary Methods Importance

Python dictionary methods are important for various reasons:

  1. The get() method allows you to retrieve the value associated with a specific key in a dictionary. It is a safer alternative to using indexing (dictionary[key]) because it returns a default value if the key is not found, preventing a KeyError from being raised.
  2. The update() method is used to add new key-value pairs to a dictionary or update the values of existing keys. It enables you to merge one dictionary with another or add multiple key-value pairs at once.
  3. The pop() method allows you to remove an item from a dictionary based on its key and retrieve its value. This is useful when you want to delete a specific entry from the dictionary and perform additional operations with its value.
  4. The keys() method returns a view object containing all the keys in a dictionary. It allows you to iterate over the keys or convert them into a list for further processing. This is valuable when you need to check the presence of specific keys or perform operations specifically on the keys.
  5. The values() method returns a view object containing all the values in a dictionary. It enables you to iterate over the values or convert them into a list for analysis or manipulation. This is beneficial when you need to check the occurrence or properties of specific values.
  6. The items() method returns a view object containing all the key-value pairs in a dictionary as tuples. It provides an iterable that allows you to access both the keys and values simultaneously. This is helpful when you need to iterate over both the keys and values or perform operations on the pairs.
  7. The len() function can be used to determine the number of key-value pairs in a dictionary. It returns the length of the dictionary, allowing you to check its size or perform comparisons with other dictionaries.
  8. Clearing a Dictionary: The clear() method removes all the key-value pairs from a dictionary, making it empty. It provides a convenient way to reset or clean a dictionary without the need for reassignment or creating a new dictionary.
  9. Copying a Dictionary: The copy() method creates a shallow copy of a dictionary. It allows you to create an independent duplicate of the original dictionary, preventing reference sharing and enabling separate modifications or operations on the copied dictionary.
  10.  The in operator can be used to check if a specific key exists in a dictionary. It returns True if the key is found and False otherwise. This is useful when you need to test for the presence of a key before performing further operations.
Keep up with the latest technical news by subscribing to our Newsletter.
We value your feedback.
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0

Subscribe To Our Newsletter
Enter your email to receive a weekly round-up of our best posts. Learn more!
icon

Leave a Reply

Your email address will not be published. Required fields are marked *