在字典中查找最高价值

时间:2016-04-17 16:05:29

标签: python dictionary

我有这样的字典:

class1 = {
          max: 10, 3, 5
          Michael: 4. 4, 8
          jack: 0, 0, 3
          }

这是相关代码

class1 = {}
        with open("1.txt", "r+") as f:
            for line in f:
                columns = line.split(":")
                if len(columns) == 2:
                    names = columns[0]
                    scores = columns[1].strip()
                else:
                    pass
                if class1.get(names):
                    class1[names].append(scores)
                else:
                    class1[names] = list(scores)

数字代表分数,我想要打印出每个名字的最高分,这是我想要的输出:

max: 10
Micheal: 8
jack: 3

我已经尝试过这个:

max_value = max(class1.values())
print(sorted(max_value))

但它对我的输出没有任何影响。

先谢谢你

2 个答案:

答案 0 :(得分:-2)

for name, l in class1:
    print("%s : %d" % (name, max(l)))

答案 1 :(得分:-2)

class1 = {}
with open("1.txt", "r+") as f:
    for line in f:
        columns = line.split(":")
        if len(columns) == 2:
            name = columns[0].strip()
            scores = map(int, columns[1].split(','))
            class1[name] = scores

for name, scores in class1.items():
    print('{}: {}'.format(name, max(scores)))