Python:在元组中为每个字段名获取最大的{(元组):值}字典

siv*_*iva 2 python dictionary tuples list max

另一个列表字典问题.

我有一个dict如下,列表中的单位名称和测试名称:

dictA = {('unit1', 'test1'): 10,  ('unit2', 'test1'): 78,  ('unit2', 'test2'): 2, ('unit1', 'test2'): 45}

units = ['unit1', 'unit2'] 
testnames = ['test1','test2']
Run Code Online (Sandbox Code Playgroud)

我们如何在测试名中找到每个测试的最大值:

我尝试如下:

def max(dict, testnames_array):
    maxdict = {}
    maxlist = []
    temp = []
    for testname in testnames_array:
        for (xunit, xtestname), value in dict.items():
            if xtestname == testname:
                if not isinstance(value, str):
                    temp.append(value)
            temp = filter(None, temp)
            stats = corestats.Stats(temp) 
            k = stats.max() #finds the max of a list using another module
            maxdict[testname] = k
    maxlist.append(maxdict)
    maxlist.insert(0,{'Type':'MAX'})
    return maxlist
Run Code Online (Sandbox Code Playgroud)

现在的问题是我得到输出:

[{'Type':'MAX'}, {'test1': xx}, {'test2':xx}]
Run Code Online (Sandbox Code Playgroud)

其中xx全部以相同的值返回!!

我的错在哪里?任何更简单的方法?请指教.谢谢.

Utk*_*glu 6

>>> dictA = {('unit1', 'test1'): 10,  ('unit2', 'test1'): 78,  ('unit2', 'test2'): 2, ('unit1', 'test2'): 45}
>>> maxDict={}
>>> for (unitName,testName),grade in dictA.items():
    maxDict[testName]=max(maxDict.get(testName,0),grade)


>>> maxDict
{'test1': 78, 'test2': 45}
Run Code Online (Sandbox Code Playgroud)

我想这应该解决它.