简体   繁体   中英

How to sort dictionary values from Highest to lowest?

My question would be how I withdraw winner based on highest score? since u cant sort in dictionaries i tried this with lists, but then name wouldnt appear, only the score...

a = {'name_a':0}
b = {'name_b':0}
c = {'name_c':0}
d = {'name_d':0}
e = {'name_e':0}

print("Each time someone scores a point, the letter of his name is typed in lowercase. If someone loses a point, the letter of his name is typed in uppercase")


score = input('Enter series of charachters indicating who scored a poitn: ')

for i in score:
    if i == 'a':
        a['name_a'] += 1
    if i == 'A':
        a['name_a'] -= 1
    if i == 'b':
        b['name_b'] += 1
    if i == 'B':
        b['name_b'] -= 1
    if i == 'c':
        c['name_c'] += 1
    if i == 'C':
        c['name_c'] -= 1
    if i == 'd':
        d['name_d'] += 1
    if i == 'D':
        d['name_d'] -= 1
    if i == 'e':
        e['name_e'] += 1
    if i == 'E':
        e['name_e'] -= 1

print(a,b,c,d,e)

print('Winner is: ', )

这将起作用:

max((i, name) for d in (a,b,c,d,e) for name, i in d.items())[1]

max_key = ""
max_val = 0

for key, value in d.items():
    if (value > max_val):
        max_val = value
        max_key = key

Is this what you mean?

you probably want to use a single dict, instead of one for each, like such:

scores = {
    'a': 0,
    'b': 0,
    'c': 0,
    'd': 0,
    'e': 0,
}

And then you can keep track of the highest scoring player as points are calculated:

point_scored = input('Enter series of charachters indicating who scored a point: ')


for i in point_scored:
    if not scores.get(i) is None:
        scores[i] += 1
    elif not scores.get(i.lower()) is None:
        scores[i.lower()] -= 1
    else:
        print(str(i) + ' is not a valid player...')

winner = max(scores, key=scores.get)

print(scores)

print('Winner is ' + winner)

我找到了答案

winner = (sorted(d.items(), key = lambda x: int(x[1]), reverse  = True))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM