![](/img/trans.png)
[英]How to find the value that occurs the most amount of times in a python dictionary?
[英]How to Find Key in Python Dictionary with Most Amount of Values (Not the Highest)?
假設我們有這本字典(較大字典的樣本):
dic = {
0: [2324, 4353, 342]
1: [242453, 542]
2: [44, 353, 5342, 5342, 5342, 534]}
我希望返回 2(鍵),因為它是具有最多值 (6) 的鍵。 因此,理想情況下的輸出如下所示:
2: 6
(鍵 2、6 個值)。
這如何在 Python 中完成?
我試過做例如print(len(dic[0]))
,它返回 3。但是,我想要的是 Python 遍歷每個鍵並為我返回最大長度,而不必手動遍歷每個.
使用帶有自定義key
的內置max
函數:
dic = {0: [2324, 4353, 342],
1: [242453, 542],
2: [44, 353, 5342, 5342, 5342, 534]}
print(max(dic.items(), key=lambda v: len(v[1]))[0])
應該打印
2
基本上,您是在告訴max
函數在比較元素時使用元組中第二個 ( [1]
) 值的長度。 .items()
方法將字典轉換為元組迭代器,因此第一個元素是鍵,第二個元素是值。
讓我假設您的數據格式類似於:
data = {
0: [1, 2, 3, 4, 5],
1: [1, 2, 5],
2: [1, 6, 9, 3, 8, 9],
5: [7]
}
下一步可能是制作包含對“key: len(value)”的字典,其中鍵和值由原始數據字典給出,例如:
dict_of_key_length_pairs = {k: len(v) for k, v in data.items()}
print(dict_of_key_length_pairs)
{0: 5, 1: 3, 2: 6, 5: 1}
然后我們需要獲取最大值的鍵(例如,鍵 2 是 6):
max(dict_of_key_length_pairs, key=dict_of_key_length_pairs.get)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.