Python Selective Keys Summation

When we work with Python dictionaries, we may face a problem in which we need to get the sum of the selective key values from the dictionary. This problem can happen in the web development domain, and let's see the following methods to solve the problem.

Method - 1: Using the list comprehension + get() + sum()

In this method, we use the get() method to access the values and traverse the dictionary using list comprehension. We perform summation using sum(). Let's understand the following example.

Example -

Output:

The original dictionary : {'javatpoint': 1, 'is': 2, 'best': 3, 'for': 4, 'Learning': 5}
9
The summation of Selective keys : 9

Method -2: Using itemgetter() + sum()

This function is specifically designed to retrieve values from a dictionary using a chain of keys as input. When called, the function returns the corresponding values as a tuple, which can then be processed further (e.g., summed) using built-in functions like sum().Let's understand the following example.

Example -

Output:

The original dictionary : {'javatpoint': 5, 'is': 12, 'best': 30, 'for': 24, 'Learning': 15}
The summation of Selective keys : 50

Time Complexity - There is N number of keys so the time complexity will be O(N).

Auxiliary space: O(1), as the space complexity is constant regardless of the size of the input.

Method - 3: Using for Loop

Let's understand the following example.

Example -

Output:

The original dictionary : {'javatpoint': 11, 'is': 20, 'best': 13, 'for': 40, 'Learning': 50}
The summation of Selective keys : 74

Time Complexity - The time complexity of the algorithm is 0(N).

Auxiliary Space - The auxiliary space complexity of the algorithm is O(k) where k is the number of keys in the key_list.

Method - 6: Using Recursive Method

The below function takes a dictionary d and list of keys and returns the sum of the values corresponding to the keys in the key list.

If the length of a list of keys is 1, the code retrieves the value associated with that key in a dictionary and returns it. Otherwise, the code retrieves the value associated with the first key in the list, and recursively calls itself with the remaining keys and the corresponding nested dictionary to obtain the final value.

This recursive process continues until the length of the keys list is reduced to 1, at which point the final value is returned. Depending on the structure of the dictionary and the nature of the keys being used, this can be an efficient way to retrieve nested values from a dictionary.

Example -

Output:

The summation of Selective keys: 94

Time Complexity - The algorithm's time complexity is 0(N).






Latest Courses