如何编写一个函数来计算文件中字典的值并将总和写入另一个文件

问题描述 投票:0回答:1

file_2.py

income = {
    "Strawberry-ice-total" : 1000,
    "Vanille-ice-total" : 2000,
    "Chocolat-ice-total" : 1500,
    "Waterice-total" : 750
}

使用 file_1 中的代码计算字典的值。我想要这个 file_2 的答案 可变总收入。

python function dictionary file count
1个回答
1
投票

file_2.py

# The dictionary containing the income values
income = { 
    "Strawberry-ice-total" : 1000, 
    "Vanille-ice-total" : 2000, 
    "Chocolat-ice-total" : 1500, 
    "Waterice-total" : 750 
}

# Import the function from file_1.py
from file_1 import count_dict_values

# Calculate total income using the function
total_income = count_dict_values(income)

# Now the variable 'total_income' contains the total income
print(f"Total income: {total_income}")

file_1.py

# Function to count the values in a dictionary
def count_dict_values(my_dict):
    return sum(my_dict.values())
© www.soinside.com 2019 - 2024. All rights reserved.