# given I want to find the x largest,
dictionary = {'cat': (3,4,5), 'meow': (6,4,1), 'dog': (1,2,3)}
x = list(dictionary.values())
lst = []
for i in x:
lst.append(sum(i))
for num in range (x-1):
final = (filter(lambda x: sum(x.key()) == lst[num] , dictionary)
print(final)
# expected answer (if x = 1):
{"cat": (3,4,5)}
#because it has the largest sum (3+4+5)
这是我到目前为止所得到的,但我在扫描字符串文字错误时得到了EOL,这意味着我甚至无法测试它是否正确。
编辑:刚试过另一种方法,看起来更简洁。但是,如何让它循环整个字典?def wrtd2(s):
dictionary = {}
for val in s:
x = max(list(s.items()), key = lambda x: sum(x[1]))
if x[0] not in dictionary:
dictionary[x[0]] = x[1]
return dictionary
答案 0 :(得分:0)
您还可以max
使用map
来检索最大值和。
然后通过词典理解过滤词典。
d = {'cat': (3,4,5), 'meow': (6,4,1), 'dog': (1,2,3)}
maxval = max(map(sum, d.values()))
res = {k: v for k, v in d.items() if sum(v) == maxval}
# {'cat': (3, 4, 5)}