如何在另一个file_1.py中编写一个函数来计算另一个file_2.py中字典的值

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

file_2.py 收入={ “草莓冰总数”:1000, “香草冰总”:2000, “巧克力冰总量”:1500, “水冰总数”:750 }

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

我已经搜索但找不到答案,我尝试了一些方法但没有成功。

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

文件_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}")

文件_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.