首页 > 解决方案 > Python打印字典键和值除以另一个变量

问题描述

嗨,我需要打印一个字典,显示键和值除以另一个变量...我尝试过的代码的任何建议如下

#Dim variables
total_votes = 0
candidate = {}
    

for row in csvreader:
    if row[2] in candidate.keys():
        candidate[row[2]] += 1
    else:
        candidate[row[2]] = 1
    total_votes += 1

for key, value  in candidate.items():
    percentage = int(value) / int(total_votes)
    print((key) + " v " + (percentage))      

    print(f"Tolal votes {total_votes}")

标签: pythondictionary

解决方案


您不能将字符串和数字相加。有几个选择。

这是一个:

#Dim variables
total_votes = 0
candidate = {}
    

for row in csvreader:
    if row[2] in candidate.keys():
        candidate[row[2]] += 1
    else:
        candidate[row[2]] = 1
    total_votes += 1

for key, value  in candidate.items():
    percentage = int(value)/int(total_votes)
    # Using commas
    print(key, " v ", percentage)      

    print(f"Tolal votes {total_votes}")

我注意到您还在下面使用了 f 字符串。对此有两个想法: f-strings 仅适用于更高版本的 python3。如果您在这里遇到错误,可能是因为您的版本。其次,您还可以使用 f-string 打印您的键和值:

print(f"{key} v {value}")

假设您的字典有效,这将起作用。


推荐阅读