Dictionary Methods in Python
A Dictionary is a native data type in Python designed to hold data as 'key: value' pairs. Dictionaries are characterized by their unordered nature (though from Python 3.7 onward, they maintain the order of insertion), mutability, and indexing, with each key being distinct and corresponding to a specific value. They are frequently utilized to organize related information, such as data linked to a particular entity or object, allowing for straightforward retrieval of the value using its associated key.
In Python, the methods associated with dictionaries are recognized as a set of different functions that perform operations on a dictionary.
Python Dictionary Methods
Numerous methods are available for Python dictionaries that allow us to execute a variety of functions, including manipulation, access, and transformation, with both efficiency and accuracy.
| Function | Explanation |
|---|---|
| fromkeys() | This method returns the dictionary with the key mapped to the value given in the "value" parameter. |
| pop() | This method is used to remove an element from the dictionary |
| clear() | This method is used to clear or delete all the elements from the dictionary. |
| popitem() | This method returns and removes the element that was added to the dictionary last. It is like last in, first out (LIFO). |
| copy() | This method returns a shallow copy of the dictionary. |
| get() | This method returns the value for the given key. |
| setdefault() | This method returns a value with a specified key. If there is no key, it will insert a key with the specified value. |
| items() | This returns all dictionary that has a value assigned. |
| keys() | This method returns a list of keys of the dictionary. |
| update() | This method is used to update the dictionary. |
| values() | This method returns a list of the dictionary values. |
Python Built-in Dictionary Methods
1. Dictionary fromkeys Method
In Python, the dictionary method fromkeys generates a new dictionary where each key is associated with the value provided in the 'value' argument. Rather than modifying the original dictionary, this method produces a fresh dictionary that follows the order of the specified keys.
Syntax:
The syntax for the fromkeys method is illustrated as follows:
dict.fromkeys(keys, value)
Parameters:
- keys: This parameter denotes the keys that will be converted into a dictionary.
- value: This is an optional parameter. It signifies the value that will be assigned to each of your keys. By default, this value is None.
Note: The value that you specify in the value parameter is assigned to all the keys of the dictionary.
Returns: This function yields a dictionary containing keys. In instances where the keys are associated with none, it does not return any value; conversely, it provides the corresponding value designated for that specific field.
Example: Dictionary fromkeys Method
Let’s examine an example to grasp how the fromkeys function operates in Python.
Example
# given set of keys
keys = {'a', 'e', 'i', 'o', 'u'}
# creating a dictionary using fromkeys()
dict_1 = dict.fromkeys(keys) # not specified any value
print("Dictionary 1 (without values):", dict_1) # set default values to none
# initializing a variable to store a value
value = 'vowel'
dict_2 = dict.fromkeys(keys, value) # specifying a default value
print("Dictionary 2 (with default value):", dict_2)
Output:
Dictionary 1 (without values): {'o': None, 'i': None, 'a': None, 'e': None, 'u': None}
Dictionary 2 (with default value): {'o': 'vowel', 'i': 'vowel', 'a': 'vowel', 'e': 'vowel', 'u': 'vowel'}
2. Dictionary pop Method
In Python, the pop function of a dictionary serves the purpose of eliminating an entry from the dictionary. This function extracts the element associated with the designated key within the specified dictionary.
When the specified key exists within the dictionary, it will be eliminated from the dictionary, and its corresponding value will be returned. Conversely, if the key is absent, a KeyError will be raised.
Syntax:
The syntax of the pop method is shown below:
dictionaryname.pop(key, defaultvalue)
Parameters:
- key: The identifier for which the associated value is to be removed.
- default_value: In the event that the key does not exist, the specified default value will be returned.
Return: This operation eliminates the entry linked with the provided key and subsequently yields the corresponding value.
Example: Dictionary pop Method
Let us examine an example to grasp how the pop function operates in Python.
Example
# simple example of Python dictionary pop() method
# given dictionary
fruits = {
'apple': 20,
'banana': 14,
'watermelon': 2,
'kiwi': 12,
'oranges': 24
}
print("Given Dictionary:", fruits)
# using the pop() method to remove the specified key
popped_value = fruits.pop('kiwi')
print("Popped Value:", popped_value)
print("Updated Dictionary:", fruits)
Output:
Given Dictionary: {'apple': 20, 'banana': 14, 'watermelon': 2, 'kiwi': 12, 'oranges': 24}
Popped Value: 12
Updated Dictionary: {'apple': 20, 'banana': 14, 'watermelon': 2, 'oranges': 24}
Explanation
In the preceding illustration, we are presented with a dictionary. We utilized the pop function to eliminate the designated key from the dictionary. Consequently, the key is deleted, and the value linked to that key is returned.
3. Dictionary clear Method
In Python, the clear method of a dictionary is utilized to eliminate, delete, or remove all items contained within the dictionary. This method removes all key-value pairs, resulting in an empty dictionary.
Syntax:
The syntax of the clear method is shown below:
NameoftheDictionary.clear
Parameters: This function does not take any input parameters.
Return Value: This function does not produce any output value.
Example: Dictionary clear Method
Let’s examine an example to comprehend how the clear method functions in Python.
Example
new_dictionary = {'1': 'Welcome', '2': 'to', '3': 'Example'}
new_dictionary.clear()
print("Printing the dictionary after .clear() method: \n", new_dictionary)
Output:
Printing the dictionary after .clear() method:
{}
Explanation
In the preceding example, we have a dictionary at our disposal. We employed the clear method to eliminate every item within the dictionary. Consequently, all items are purged, resulting in an empty dictionary being returned.
4. Dictionary popitem Method
In Python, the popitem function is utilized to extract and remove the most recently added key-value pair from a dictionary. If the dictionary is devoid of items, a KeyError will be triggered to indicate the absence of elements.
Syntax:
The structure of the popitem function is illustrated as follows:
NameoftheDictionary.popitem
Parameters: This function does not take any input parameters.
Return Value: This function generates a fresh dictionary by eliminating the most recently added entry from the original dictionary.
Example: Dictionary popitem Method
Let's examine an example to grasp how the popitem function operates in Python.
Example
dictionary_data = {'Welcome': 1, 'to': 2, 'Example': 3}
item = dictionary_data.popitem()
print("The item is:",item)
print("The dictionary obtained is:",dictionary_data)
Output:
The item is: ('Example', 3)
The dictionary obtained is: {'Welcome': 1, 'to': 2}
Explanation
In the preceding illustration, a dictionary is provided. We utilized the popitem function to eliminate the most recently added entry from the dictionary. Consequently, after the removal of the last added item, a new dictionary is generated.
5. Dictionary copy Method
In Python, the copy function serves the purpose of generating and returning a shallow duplicate of the dictionary.
A shallow copy generates a new object that mirrors the structure of the original object, excluding its nested elements. The properties at the top level are transferred into a new dictionary, whereas any objects referenced within it continue to link to the same memory addresses as those in the original object. To summarize, only the outer container is replicated, while the underlying reference values stay unchanged.
Syntax:
The syntax of the copy method is shown below:
NameoftheDictionary.copy
Parameters: This function does not take any input parameters.
Return Value: This function generates a shallow duplicate of the existing dictionary.
Example: Dictionary copy Method
Let’s examine an example to gain insights into how the copy method functions in Python.
Example
first_dictionary = {'Name': 'Example', 'Topic': 'Python Copy Method'};
second_dictionary = first_dictionary.copy()
print ("New Dictionary : %s" % str(second_dictionary))
Output:
New Dictionary : {'Name': 'Example', 'Topic': 'Python Copy Method'}
Explanation
In the preceding example, we have a dictionary referred to as firstdictionary. Subsequently, we produced a shallow copy of this dictionary, which was assigned to a new dictionary called seconddictionary, and then we displayed the output.
Example: Updating the elements of a Dictionary
Here is an illustration of modifying the elements within a dictionary by utilizing the copy method:
Example
first_dictionary = {1: 'Example', 2: 'Python Dictionary Methods', 3: [2, 0, 5]}
print("The given dictionary is: ", first_dictionary)
# using copy() method to copy
new_dictionary = first_dictionary.copy()
print("The new copied dictionary is: ", new_dictionary)
# Updating the elements in the second dictionary
new_dictionary[1] = 'Python Copy Method'
# updating the items in the list
new_dictionary[3][2] = 404
print("The updated dictionary is: ", new_dictionary)
Output:
The given dictionary is: {1: 'Example', 2: 'Python Dictionary Methods', 3: [2, 0, 5]}
The new copied dictionary is: {1: 'Example', 2: 'Python Dictionary Methods', 3: [2, 0, 5]}
The updated dictionary is: {1: 'Python Copy Method', 2: 'Python Dictionary Methods', 3: [2, 0, 404]}
Explanation
In the preceding example, we have a dictionary referred to as firstdictionary. We created a new dictionary called newdictionary by duplicating the elements from first_dictionary, and subsequently, we displayed its contents.
Subsequently, we modified the components of the new_dictionary and displayed the results.
6. Dictionary get Method
In Python, the get function is utilized to retrieve the value associated with a key that the user specifies. Should the key not exist within the dictionary, the function will return None.
Syntax:
The syntax of the get method is shown below:
NameoftheDictionary.get(key, value)
Parameters:
- key: This key is determined by the user and is utilized to locate the corresponding entry in the dictionary.
- value: The value linked to the provided key will be returned. In the event that the key is not found, the function will yield None.
Example: Dictionary get Method
Let's examine an example to grasp how the get method functions in Python.
Example
car_details = {
"brand": "Tata",
"model": "Sierra",
"year": 2025
}
a = car_details.get("model")
print(a)
Output:
Sierra
Explanation
In the preceding illustration, there exists a dictionary referred to as car_details, which contains information pertaining to various cars. We utilized the get function to retrieve the value associated with the -model- key from this dictionary.
Example: When the Key does not exist
Let's examine an example to understand the outcome when a key is absent while utilizing the get method:
Example
car_details = {
"brand": "Tata",
"model": "Sierra",
"year": 2025
}
a = car_details.get("kilometres_driven")
print(a)
Output:
Explanation
In the preceding illustration, we possess a dictionary referred to as car_details that contains information regarding a vehicle, including its brand, model, and manufacturing year.
Utilizing the get method, we attempt to retrieve the value associated with the key "kilometres_driven." However, since this key is not present in the dictionary, the get function yields None rather than throwing an error. Consequently, the final output is None.
7. Dictionary setdefault Method
In Python, the setdefault function is employed to retrieve a value associated with a given key. If the key does not exist, it will add the key with the designated value. By default, the value assigned to the key is None.
Syntax:
The structure of the setdefault function is illustrated as follows:
NameoftheDictionary.setdefault(key, default=None)
Parameters
- key: This parameter represents the key provided by the user, which is intended to be located within the dictionary.
- value: In the event that the key cannot be located, this value will be returned. By default, it is set to None.
Example: Dictionary setdefault method
Let’s explore an example to grasp how the setdefault function operates in Python.
Example
#Creating a dictionary
dictionary = {'Car Brand': 'Tata', 'Model': 'Sierra'}
# printing the first result
print ("Value : %s" % dictionary.setdefault('Model'))
Output:
Value : Sierra
Explanation
In the preceding illustration, there exists a dictionary that includes keys for Car Brand and Model, with their corresponding values being Tata and Sierra. Subsequently, we accessed the Model key from the dictionary, which yielded -Sierra- as the result.
Example: None Default Value
Let us examine an example to grasp the importance of the default value set to None.
Example
#Creating a dictionary
dictionary = {'Car Brand': 'Tata', 'Model': 'Sierra'}
#key doesn't exist
print ("Value : %s" % dictionary.setdefault('Age'))
Output:
Value : None
Explanation
In the previously mentioned illustration, there exists a dictionary that includes keys for Car Brand and Model, with their corresponding values being Tata and Sierra, respectively. Subsequently, we attempted to display the value associated with the key -Age-; however, as that key is not present in the dictionary, the default value of None is returned.
8. Dictionary items Method
The items function in Python is utilized to retrieve all key-value pairs from a dictionary that has an assigned value.
Upon updating a dictionary, the items that are returned will also reflect those changes. It is important to note that dictionaries are unordered collections (though from Python 3.7 onwards, they maintain the order of insertion), mutable, and indexed, with each key being distinct and corresponding to a specific value. They are typically utilized for organizing related data, such as details linked to a particular entity or object, allowing for straightforward retrieval of values based on their associated keys.
Syntax:
The syntax of the items method is shown below:
The syntax for the items method is as follows:
NameoftheDictionary.items
Parameters: This function does not take any arguments.
Return Value: The item function provides output as a list containing tuples that represent key-value pairs.
Example: Dictionary items method
Let’s explore an example to comprehend how the items method functions in Python.
Example
dictionary = {'A': 'Example', 'B': 'Python', 'C': 'Dictionary', 'D': 'Methods'}
# using items() to get all key-value pairs
items = dictionary.items()
print(items)
Output:
dict_items([('A', 'Example'), ('B', 'Python'), ('C', 'Dictionary'), ('D', 'Methods')])
Explanation
In the example provided, we constructed a dictionary and displayed all elements contained within the key-value pairs, which are organized as a tuple nested within the dictionary.
Example: Updating the Dictionary
Let us examine an example of modifying a dictionary by utilizing the items method in Python.
Example
dictionary = {'A': 'Example', 'B': 'Python', 'C': 'Dictionary', 'D': 'Methods'}
# using items() to get all key-value pairs
items = dictionary.items()
print(items)
#updating the dictionary
dictionary['A'] = 'Welcome to our tutorial'
print("Dictionary after updating: ", items)
Output:
dict_items([('A', 'Example'), ('B', 'Python'), ('C', 'Dictionary'), ('D', 'Methods')])
Dictionary after updating: dict_items([('A', 'Welcome to our tutorial'), ('B', 'Python'), ('C', 'Dictionary'), ('D', 'Methods')])
Explanation
In the preceding illustration, a dictionary was established, and we displayed all the items contained in key-value pairs formatted as tuples within that dictionary. Subsequently, we modified the value associated with the 'A' key, changing it from 'Example' to 'Welcome to our tutorial,' and then we printed the modified dictionary.
9. Dictionary keys Method
This approach is utilized to retrieve and provide the collection of keys from the dictionary.
Syntax:
The syntax of the keys method is shown below:
NameoftheDictionary.keys
Arguments: This function does not take any arguments.
Return Value: The item method yields a list containing the keys from the dictionary.
Example: keys method
Let’s explore an example to gain a clearer understanding of how the keys method operates in Python.
Example
#Creating a dictionary
car_details = {'Car Brand': 'Tata', 'Model': 'Sierra', 'Year': 2025}
# extracts and prints the keys of the dictionary
keysmethod= car_details.keys()
print(keysmethod)
Output:
dict_keys(['Car Brand', 'Model', 'Year'])
Explanation
In the preceding example, we possess a dictionary named car_details that contains both keys and their corresponding values. We utilize the keys method to retrieve and display solely the keys, which include 'Car Brand', 'Model', and 'Year'.
Example: Updating the Dictionary
Let's examine an illustration of modifying a dictionary by utilizing the keys method in Python.
Example
#Creating a dictionary
car_details = {'Car Brand': 'Tata', 'Model': 'Sierra', 'Year': 2025}
# extracts and prints the keys of the dictionary
keysmethod= car_details.keys()
print('Before the update of dictionary:', keysmethod)
#updating the dictionary
# adding an element to the dictionary
car_details.update({'price': '11.99 Lakhs only'})
# prints the updated dictionary
print('Dictionary after the update:', keysmethod)
Output:
Before the update of the dictionary: dict_keys(['Car Brand', 'Model', 'Year'])
Dictionary after the update: dict_keys(['Car Brand', 'Model', 'Year', 'price'])
Explanation
In the preceding illustration, we possess a dictionary named car_details that contains both keys and their corresponding values. We utilize the keys method to retrieve and display solely the keys, which include 'Car Brand', 'Model', and 'Year'. Subsequently, we introduced a new element and printed the keys of the modified dictionary, which now included the newly added -price-.
10. Dictionary values Method
The values function provides the capability to obtain a view object that includes all the values present in the dictionary, enabling efficient access and iteration.
Syntax:
The syntax of the values method is shown below:
NameoftheDictionary.values
Parameters: This function does not take in any parameters.
Return Value: The values method produces a list containing the values from the dictionary.
Example: Dictionary values Method
Let's examine an illustration that demonstrates the application of the values method in Python.
Example
#Creating a dictionary
car_details = {'Car Brand': 'Tata', 'Model': 'Sierra', 'Year': 2025}
# extracts and prints the values of the dictionary
valuesmethod= car_details.values()
print(valuesmethod)
Output:
dict_values(['Tata', 'Sierra', 2025])
Explanation
In the preceding illustration, there exists a dictionary named car_details that contains both keys and their corresponding values. We employ the values method to retrieve and display just the values, which are 'Tata', 'Sierra', and 2025.
Example: Updating the Dictionary
Let’s examine an instance of modifying a dictionary by utilizing the values method in Python.
Example
#Creating a dictionary
car_details = {'Car Brand': 'Tata', 'Model': 'Sierra', 'Year': 2025}
# extracts and prints the values of the dictionary
valuesmethod= car_details.values()
print("The values of the dictionary before appending are: ", valuesmethod)
# Appending an item to the dictionary
car_details['Fuel Type'] = 'Petrol'
# Printing the result
print ("The values of the dictionary after appending are: ", valuesmethod)
Output:
The values of the dictionary before appending are: dict_values(['Tata', 'Sierra', 2025])
The values of the dictionary after appending are: dict_values(['Tata', 'Sierra', 2025, 'Petrol'])
Explanation
In the preceding example, there exists a dictionary named car_details that contains various keys along with their corresponding values. We utilize the values method to retrieve and display the current values of the dictionary prior to any updates, which include 'Tata', 'Sierra', and 2025.
Subsequently, we added a new entry to the dictionary by introducing a key labeled -Fuel_Type- with the corresponding value set to Petrol. Following this, we executed a print statement to display the values, resulting in the output: (['Tata', 'Sierra', 2025, 'Petrol']).
11. Dictionary update Method
The update function is utilized to modify the elements within a dictionary or an iterable collection that contains key-value pairs.
Syntax:
The syntax of the update method is shown below:
NameoftheDictionary.update([other])
Parameters: This function takes in the elements that need to be substituted using either a dictionary or an iterable collection of key/value pairs.
Return Value: The values function yields the dictionary or iterable collections of key-value pairs containing the modified elements.
Example: Dictionary update Method
Let’s examine a basic illustration that demonstrates the application of the update method in Python.
Example
# using the update() method in Dictionary
# Dictionary with three items
first_dictionary = {'A': 'Example', 'B': 'Python', }
second_dictionary = {'B': 'Dictionary', 'C': 'Methods'}
# updating first dictionary
first_dictionary.update(A='Welcome to our tutorial')
print(first_dictionary)
#updating second dictionary
second_dictionary.update(B='We are learning Dictionary')
print(second_dictionary)
Output:
{'A': 'Welcome to our tutorial', 'B': 'Python'}
{'B': 'We are learning Dictionary', 'C': 'Methods'}
Explanation
In the preceding illustration, we possess two dictionaries, designated as firstdictionary and seconddictionary. The update function was employed to modify the value associated with key A, changing it from -C# Tutorial- to -Welcome to our tutorial-, and similarly, the value for key B was altered from -Dictionary- to -We are learning Dictionary- in both dictionaries, correspondingly.
Instance: Modifying the Dictionary Using Keyword Arguments
Let's examine an illustration of how to modify a dictionary using keyword arguments in Python.
Example
#updating the dictionary with only keyword arguments
# Here we have only one dictionary
dictionary = {'A': 'T'}
# Update the Dictionary with an iterable
dictionary.update(B='point', C='Tech')
print(dictionary)
Output:
'A': 'T', 'B': 'point', 'C': 'Tech'}
Explanation
In the preceding illustration, we are presented with a dictionary that consists of just one key-value pair. We subsequently employed the update method, utilizing solely keyword arguments to introduce additional elements into the dictionary. Following this, two new keys, B and C, were incorporated with the values 'point' and 'Tech', respectively. It is important to note that these keys were absent from the dictionary prior to this action; they were added through the utilization of the update method. Ultimately, when we printed the dictionary, it displayed all three key-value pairs: A, B, and C.
Conclusion
In concluding this comprehensive tutorial on Dictionary Methods in Python, let us briefly summarize what we have covered. A Dictionary is a fundamental data structure provided by Python, utilized for storing data as 'key: value' pairs. These dictionaries are characterized as unordered, mutable, and indexed collections, where every key is distinct and corresponds to a specific value. Python offers a variety of built-in methods for dictionaries, including fromkeys, pop, clear, popitem, copy, setdefault, get, items, keys, values, and update. We have explored each of these methods thoroughly, accompanied by numerous examples.
Python Dictionary Methods FAQs
1. What are Dictionaries in Python?
A Dictionary is an intrinsic data type in Python that facilitates the organization of data as 'key: value' pairs. These collections are unordered, mutable, and indexed, ensuring that each key is distinct and corresponds to a specific value. Typically, dictionaries are employed to maintain related information, such as data tied to a particular entity or object, allowing for straightforward retrieval of the value using its associated key.
2. What are Dictionary Methods in Python?
In Python, the methods associated with dictionaries are recognized as a set of different functions that perform operations on a dictionary.
3. What is the difference between pop and popitem?
The pop function serves the purpose of eliminating an element from the dictionary. Specifically, this function extracts the element associated with the designated key within the provided list. In contrast, the popitem function is utilized to discard the most recently added item, which consists of a key-value pair, from the dictionary.
4. What does the copy method do?
The copy function is utilized to generate and return a shallow copy of a dictionary. A shallow copy produces a new object that mirrors the structure of the original object, excluding its nested elements. In essence, only the container itself is replicated, while the references to the actual values are kept unchanged.
5. What is the difference between the clear method and deleting the dictionary?
In Python, the clear function serves the purpose of emptying a dictionary by eliminating all its elements. Importantly, this method ensures that the dictionary object itself remains intact. In contrast, employing del dictionary not only removes the contents but also completely deletes the reference to the dictionary from memory.