Python - Value Summation of a key in the Dictionary


Introduction

The Python programming language is an advanced−level, versatile programming language used for widespread usage for diverse purposes. The software consists of web design, data analytics, and AI. People are aware because of its straightforwardness, legibility, and convenience in usability. Python offers various predefined data structures, which include lists, tuples, maps, sets, piles, and lineups. These components are vital in every programming language. Within this post, we will concentrate on lexicons, that are utilized to save key−information pairs.

Maps are a crucial data component in Python that enable people to store key and data pairs. These are comparable to associative arrays in various programming frameworks. These are intended to save and access data rapidly. Within a reference book, the elements should be distinct. The elements, conversely, can belong to any data category. Maps are changeable, which implies that you can append, eliminate, or adjust element−value pairs as required. We plan to explore the fundamentals of dictionaries and the significance they hold. Moreover, we are going to learn the process of performing the total calculation of an identifier inside a map using Python programming language.

Definition

In the Python programming language, a mapping represents an unordered container for storing keys and their respective values. The elements within a hash map can store any data category and can be obtained by pointing to their corresponding identifiers. Adding up the values linked to a particular key within a dictionary entails extracting the values that match the designated key.

Syntax

sum_of_values = sum(dictionary[key])
  • ‘dictionary’: The name of the dictionary from which the values should be extracted.

  • ‘key’: The particular key for which we wish to compute the sum of values.

  • ‘Sum’: A Python function that calculates the sum of all the elements in an iterable.

Algorithm

  • Step 1: Set up a variable for storing the addition of values.

  • Step 2: The dictionary's list of values associated with the supplied key can be accessed.

  • Step 3: To compute the sum of the values, use the sum() function.

  • Step 4: Assign the sum to the variable that was created in Step 1.

  • Step 5: The sum of values should be printed or returned.

Approach

  • Approach 1: Using a loop−based approach

  • Approach 2: Using sum() and dict.values()

Approach 1: Using a loop−based approach

Example

my_dict = {"a": [1, 5], "b": 2, "c": 3, "d": 4}
key_to_sum = "a"

total_sum = 0
for key, value in my_dict.items():
    if key == key_to_sum:
        total_sum += sum(value)

print(total_sum)

Output

6

Initially, the map `my_dictionary` is prepared with key and value pairs. As an illustration, the letter 'a' is linked to a collection of values [1, 5]. The key 'b', 'c', and 'd' are linked to whole number values.

Then, the object `sum_key` is declared. This symbolizes the value for that we wish to determine the aggregate of connected values. In this situation, `key_to_sum`'s value equals `'a'`.

This variable `total_sum` gets set to zero. The variable will gather the total of the elements linked to the reference defined by `sum_key`.

The software executes a `for` loop. This loop through every item in the `my_dict` map. Throughout every loop, the program verifies provided that the current identifier matches the assigned key. This process does so by checking the input `key` in comparison to the value `key_to_sum`.

If the key is equal, the program runs the section within the conditional code. This utilizes the `total()` function to compute the addition of the elements linked to the label `'a'`. The value `'b'` is indicated by the collection `[3, 7]`. The computed total is then joined with the variable `total_sum`.

Once the iteration is complete over the entirety of the associations between keys and values inside the `my_dict`, the loop reaches its conclusion. The program then continues to the subsequent line in the script. It shows the result contained in the `total_sum` variable. In this specific example, these values linked with the identifier `'a'` are `[1, 5]`. The program computes the total of the given numbers, leading to `half a dozen`. Thus, the result generated by the script shall be the number `6`.

Approach 2: Using sum() and dict.values()

Example

wages = {'01': 910.56, '02': 1298.68, '03': 1433.99, '04': 1050.14, '05': 877.67}
total = sum(wages.values())
print('Total Wages: ${0:,.2f}'.format(total))

Output

Total Wages: $5571.04

This code uses a straightforward method utilizing pre−existing Python functions for computing the total of elements contained in the `wages` dictionary and arranging the outcome.

Then, the `sum()` function is utilized to compute the total among all the elements in the `wages` map. The `sum()` method is an inherent method in Python that accepts a sequence as a parameter and returns the addition of the entire set in the collection. In this scenario, the collection denotes the entries contained in the `wages` dictionary. Bypassing the entries from the `wages` dictionary for the `sum()` function, it is possible to easily determine the overall total of the income. By using `wages.values()` as a parameter in `total()`, it gets the values from the dictionary.

The computed total is afterward recorded within the container `total`. In the future, the `output()` function is employed to present the outcome. The format string `'Total Wages: ${0:,.2f}'` is implemented to set the display format. In this format string, `{0:,.2f}` serves as a substitute for this `total` number. The `0` the placeholder represents the index of the value being formatted. The `:,.2f` portion sets the formatting preferences. `,:` includes commas as separators for thousands for better readability. `2 digits after the decimal point` ensures the value is presented with two decimal places.

This method is invoked on the string used for formatting to exchange the value stored in `total` into the designated space. This leads to the intended output format. The result represents the overall total income in the `wages` dataset. The total appears using a monetary symbol, thousands separated by commas, and two digits after the decimal point to achieve exactness.

Conclusion

Dictionaries are among the most crucial and often utilized data structures in computer studies. These are applied to a diverse array of purposes. These software programs incorporate data analysis, artificial intelligence, website creation, and additional tasks. A dictionary enables users to easily retrieve the facts related to a specific keyword.

Dictionaries, a feature of Python can be used in various ways storage structures. Having the capability to effectively control the data they possess is a crucial competence for all programmers in Python. Regardless of whether predefined functions or user−defined logic, the capability to execute mathematical computations and tasks on key−value pairs leads to greater potent and successful Python programs.

Updated on: 27-Jul-2023

97 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements