gpt4 book ai didi

python - 在字典中查找具有最多值的键

转载 作者:行者123 更新时间:2023-11-28 21:08:04 25 4
gpt4 key购买 nike

我正在开发一个函数,我需要在字典中找到具有最多值的键(艺术家姓名)。有时两个键具有相同数量的值,在这种情况下,我需要返回艺术家姓名列表。

示例字典:

{'M':[("One",1400,30.0, 20.5,"oil paint","Austria"),("Three",1430,100.0,102.0,"watercolor","France")],
'P':[("Eight",1460, 225.0, 200.0, "fresco","Netherlands")],
'U':[("Nine",1203,182.0, 957.0,"egg tempera","Italy"), ("Twelve",1200,76.2,101.6,"egg tempera","France")]
}

对于这个字典,因为 M 和 U 有最多的值(M 有 2,U 有 2 而 P 只有 1)函数应该返回

artists_with_most_work(dictionary1())

['M', 'U']

我如何搜索每个键值的数量并返回拥有最多的值?我认为使用 max() 是个好主意,但我认为我在下面的当前尝试中没有正确使用它。感谢任何可以提供帮助的人

代码:

def artist_with_most_work(db):
matches = []
for key, record_list in db.items():
for record in record_list:
if item in record:
max(db) = themax
matches.append(themax)
return matches

最佳答案

您必须首先找到最大长度,然后返回引用具有该长度的列表的所有键:

def artist_with_most_work(db):
maxcount = max(len(v) for v in db.values())
return [k for k, v in db.items() if len(v) == maxcount]

演示:

>>> def artist_with_most_work(db):
... maxcount = max(len(v) for v in db.values())
... return [k for k, v in db.items() if len(v) == maxcount]
...
>>> d1 = {'M':[("One",1400,30.0, 20.5,"oil paint","Austria"),("Three",1430,100.0,102.0,"watercolor","France")],
... 'P':[("Eight",1460, 225.0, 200.0, "fresco","Netherlands")],
... 'U':[("Nine",1203,182.0, 957.0,"egg tempera","Italy"), ("Twelve",1200,76.2,101.6,"egg tempera","France")]
... }
>>> artist_with_most_work(d1)
['M', 'U']

关于python - 在字典中查找具有最多值的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40598532/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com