Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
241 views
in Technique[技术] by (71.8m points)

Python printing dictionary key and value divided by another variable

Hi I need to print a Dictionary showing the key and the value divided by another variable ... any suggestions the code I have tried is below

#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}")
question from:https://stackoverflow.com/questions/65640683/python-printing-dictionary-key-and-value-divided-by-another-variable

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can't add a string and a numerical together. There are a couple options.

Here's one:

#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}")

I notice you've also used a f-string below. Two thoughts on this: f-strings only work on later versions of python3. If you're having an error here, it may be because of your version. Second, you can also use an f-string to print your key and value:

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

Assuming your dictionary is valid, this will work.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...