需要从具有最高值的字典中返回元组

时间:2018-04-19 01:27:15

标签: python python-3.x dictionary

这是我到目前为止的代码:

def most_oscars(d):
    v=list(d.values())
    k=list(d.keys())
    return k[v.index(max(v))]

当前输出:

Meryl Streep

但它需要像('Meryl Streep', 20)

那样打印

我需要添加/更改什么?

3 个答案:

答案 0 :(得分:0)

一种方法是使用operator.itemgetter

import operator

def most_oscars(d):
    return max(d.items(), key=operator.itemgetter(1))

nominees = {'Meryl Streep': 20, 'Robert De Niro': 7, 'Michael Caine': 6, 'Maggie Smith': 6}

print(most_oscars(nominees))

# ('Meryl Streep', 20)

答案 1 :(得分:0)

由于两个actor拥有相同的最大奥斯卡数是完全可行的,因此您可以使用列表推导来返回元组列表:

def most_oscars(d):
    maxval = max(d.values())
    return [(k, v) for k, v in d.items() if v == maxval]

nominees = {'Meryl Streep': 20, 'Robert De Niro': 20, 'Michael Caine': 6, 'Maggie Smith': 6}

print(most_oscars(nominees))

# [('Meryl Streep', 20), ('Robert De Niro', 20)]

答案 2 :(得分:0)

试试这个

def most_oscars(d):
    max_key = max(d, key=d.get)
    reslt_pair = tuple([max_key,d[max_key]])
    print(reslt_pair)
相关问题