打印字典值从最高到最低

时间:2016-05-05 19:22:03

标签: python dictionary

这不是重复的,因为编写代码的方式使我无法使用我研究堆栈溢出的方法。

  1. 我有这样的字典:

    class_dictionary: {'John':[2,3,4], 'Mark':[6,9,4], 'James':[0,0,0]}
    

    我需要打印每个字符从最高到最低的值最高的名称。我已经写过:

    for names, scores in class_dictionary.items():
            print("{} : {}".format(names, max(scores)))
    

    这会打印出每个学生的最高价值但不按顺序排列。像这样:

    John: 4
    James: 0
    Mark: 9
    

    期望的输出:

    Mark: 9
    John: 4
    James: 0
    

    我如何将这些结果打印到最低到最低?

  2. 我有这样的字典:

    class_dictionary: {'John':[2,3,4], 'Mark':[6,9,4], 'James':[0,0,0]}
    

    我需要打印名称,每个人的平均值从最高到最低。我已经写过:

    pprint({k: [sum(float(i) for i in v) / len(v)] for k, v in class_dictionary.items()})
    

    这打印出每个学生的平均值,但不是按顺序。像这样:

    John: 3
    Mark: 6.33333
    James: 0
    

    如何将这些结果打印出最高到最低?

    期望的输出:

    Mark: 6.33333
    John: 2
    James: 0
    
  3. 如果您打算投票,请解释原因,以便我下次可以改进问题。

3 个答案:

答案 0 :(得分:2)

您只需在打印前进行排序:

var MyCtrl = function($route, $scope, $log, $http, $sce, $q, $filter) {

    var vm = this;
    vm.$route = $route;
    vm.$scope = $scope;
    vm.$log = $log;
    vm.$http = $http;
    vm.$sce = $sce;
    vm.$q = $q;
    vm.$filter = $filter;
    vm.activate = activate() ;

    activate()

   function activate() {
        vm.ShouldAutoStart = false;
        vm.viewA = true;
        vm.viewB = false;
        vm.topButtonClicked = false;
        vm.showIDTable = false;
        vm.topRequest;
    }
};

打印:

d = {'John': [2,3,4], 'Mark': [6,9,4], 'James': [0,0,0]}

# Both of the lists below can be generators as well, just change surrounding [] to ()
# Generate a list containing names and highest scores only
highest_scores = [(name, max(scores)) for (name, scores) in d.items()]
# Generate a list containing names and averages only
averages = [(name, sum(scores)/float(len(scores))) for (name, scores) in d.items()]

# Every item is a tuple of name and score, so sort by item[1] (which is the score)
sort_key = lambda item: item[1]

for name, score in sorted(highest_scores, key=sort_key, reverse=True):
    print("%s: %d" % (name, score))

for name, avg in sorted(averages, key=sort_key, reverse=True):
    print("%s: %f" % (name, avg))

答案 1 :(得分:0)

将最大值存储在临时字典中,然后再次对其进行排序

class_dictionary= {'Jhon':[2,3,4], 'Mark':[6,9,4], 'James':[0,0,0]}

tmp = {}
for names, scores in class_dictionary.items():
     tmp[names] = max(scores)

print sorted(tmp.items(), reverse=True, key=lambda (k,v) : v )

你明白了。试试你的第二个问题并发布你走了多远,哪些没有用。

答案 2 :(得分:0)

import pandas as pd

class_dictionary =  {'Jhon':[2,3,4], 'Mark':[6,9,4], 'James':[0,0,0]}

test_df = pd.DataFrame(class_dictionary)

max_df =  test_df.max().sort_values(ascending = False)
print max_df

mean_df =  test_df.mean().sort_values(ascending = False)
print mean_df