Python - Summing the values ​​of keys in a dictionary

WBOY
Release: 2023-09-05 23:05:02
forward
1609 people have browsed it

Python - 字典中键的值求和

简介

Python 编程语言是一种高级、多功能的编程语言,广泛用于多种目的。该软件由网页设计、数据分析和人工智能组成。人们之所以意识到它是因为它的简单性、易读性和易用性。 Python 提供了各种预定义的数据结构,包括列表、元组、映射、集合、堆和队列。这些组件对于每种编程语言都至关重要。在这篇文章中,我们将重点关注用于保存关键信息对的词典。

地图是 Python 中的重要数据组件,使人们能够存储密钥和数据对。它们与各种编程框架中的关联数组相当。这些旨在快速保存和访问数据。在参考书中,元素应该是不同的。相反,元素可以属于任何数据类别。映射是可变的,这意味着您可以根据需要追加、消除或调整元素-值对。我们计划探索字典的基础知识及其意义。此外,我们将学习使用Python编程语言在地图内执行标识符的总计算的过程。

定义

在Python编程语言中,映射表示用于存储键及其各自值的无序容器。哈希映射内的元素可以存储任何数据类别,并且可以通过指向其相应的标识符来获取。添加链接到字典中特定键的值需要提取与指定键匹配的值。

语法

sum_of_values = sum(dictionary[key])
Copy after login
  • “dictionary”:应从中提取值的字典的名称。

  • “key”:我们希望计算其值总和的特定键。

  • “Sum”:一个 Python 函数,用于计算可迭代对象中所有元素的总和。

算法

  • 第 1 步:设置一个变量来存储相加的值。

  • 第 2 步:可以访问与所提供的键关联的字典值列表。

  • 第 3 步:要计算值的总和,请使用 sum() 函数。

  • 第 4 步:将总和分配给第 1 步中创建的变量。

  • 第 5 步:应打印或返回值的总和。

方法

  • 方法 1:使用基于循环的方法

  • 方法 2:使用 sum() 和 dict.values()

方法 1:使用基于循环的方法

示例

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)
Copy after login

输出

6
Copy after login

最初,映射“my_dictionary”是用键和值对准备的。作为说明,字母“a”链接到值的集合 [1, 5]。键“b”、“c”和“d”链接到整数值。

然后,声明对象“sum_key”。这象征着我们希望确定连接值的聚合的值。在这种情况下,`key_to_sum`的值等于`'a'`。

此变量“total_sum”设置为零。该变量将收集链接到“sum_key”定义的引用的元素总数。

软件执行“for”循环。此循环遍历“my_dict”映射中的每个项目。在每个循环中,程序都会验证当前标识符是否与分配的键匹配。此过程通过检查输入“key”与值“key_to_sum”的比较来实现此目的。

如果键相等,程序将运行条件代码中的部分。它利用“total()”函数来计算链接到标签“a”的元素的相加。值“b”由集合“[3, 7]”表示。然后将计算出的总计与变量“total_sum”连接起来。

一旦完成了“my_dict”内键和值之间的整个关联的迭代,循环就会得出结论。然后程序继续执行脚本中的下一行。它显示了“total_sum”变量中包含的结果。在这个具体示例中,与标识符“a”链接的这些值是“[1, 5]”。该程序计算给定数字的总数,得出“六个”。因此,脚本生成的结果应为数字“6”。

方法 2:使用 sum() 和 dict.values()

示例

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))
Copy after login

输出

Total Wages: $5571.04
Copy after login

此代码使用一种简单的方法,利用预先存在的 Python 函数来计算“工资”字典中包含的元素总数并排列结果。

然后,使用“sum()”函数计算“工资”映射中所有元素的总和。 sum() 方法是 Python 中的固有方法,它接受序列作为参数并返回集合中整个集合的相加。在这种情况下,集合表示“工资”字典中包含的条目。绕过“sum()”函数的“wages”字典中的条目,可以轻松确定收入总额。通过使用“wages.values()”作为“total()”中的参数,它从字典中获取值。

计算出的总数随后记录在容器“total”中。将来,将使用“output()”函数来呈现结果。实现格式字符串“Total Wages: ${0:,.2f}”来设置显示格式。在此格式字符串中,“{0:,.2f}”用作此“total”数字的替代。占位符“0”表示正在格式化的值的索引。 `:,.2f` 部分设置格式首选项。 `,:` 包含逗号作为千位分隔符,以提高可读性。 “小数点后 2 位”确保该值显示两位小数。

Call this method on the string used for formatting to swap the value stored in "total" into the specified space. This results in the expected output format. The result represents the overall total earnings in the Salary data set. Totals are shown using currency symbols, thousands separated by commas, and two digits after the decimal point to ensure accuracy.

in conclusion

Dictionary is one of the most important and commonly used data structures in computer research. These are suitable for a variety of purposes. These software programs include data analysis, artificial intelligence, website creation, and other tasks. Dictionaries enable users to easily retrieve facts related to specific keywords.

Dictionaries are a feature of Python that can use storage structures in a variety of ways. Having effective control over the data at your disposal is a critical capability for all Python programmers. Whether it's predefined functions or user-defined logic, the ability to perform mathematical calculations and tasks on key-value pairs leads to more efficient and successful Python programs.

The above is the detailed content of Python - Summing the values ​​of keys in a dictionary. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!