Problem Formulation
π¬ Programming Challenge: Given a dictionary where the values are lists of varying sizes. Find and return the longest list!
Here’s an example:
d = {1: [1, 2, 3], 2: [1, 2], 3: [1], 4: [1, 2, 3, 4]} # Goal: [1, 2, 3, 4]
Also, you’ll learn how to solve a variant of this challenge.
π¬ Bonus challenge: Find only the key that is associated with the longest list in the dictionary.
Here’s an example:
d = {1: [1, 2, 3], 2: [1, 2], 3: [1], 4: [1, 2, 3, 4]} # Goal: 4
So without further ado, let’s get started!
Method 1: max(lst, key=len)
Use Pythonβs built-in max()
function with a key argument to find the longest list from the dictionary values. Call max(d.values(), key=len)
to return the longest list in d.values()
using the built-in len()
function to associate the weight of each list, so that the longest list will be the maximum.
Here’s an example:
d = {1: [1, 2, 3], 2: [1, 2], 3: [1], 4: [1, 2, 3, 4]} print(max(d.values(), key=len)) # [1, 2, 3, 4]
A beautiful one-liner solution, isn’t it? π Let’s have a look at a slight variant to check the key of the longest list instead.
Method 2: len(max(lst, key=len))
To get the key mapping to the longest list value in a dictionary, use max(d, key=lambda x: len(d[x]))
.
Explanation: You set the key argument of max()
to a lambda function that maps each dictionary key x
to the length of the associated value obtained with len(d[x])
. This way, you use the length of the mapped values as weights to determine the “maximum”, i.e., the longest list.
π‘ Note: When you call max(d)
Python will automatically replace it with max(d.keys())
, so it iterates over the keys of the dictionary.
Here’s an analogous example:
d = {1: [1, 2, 3], 2: [1, 2], 3: [1], 4: [1, 2, 3, 4]} print(max(d, key=lambda x: len(d[x]))) # 4
The key with longest list in the dictionary is 4
.
π Recommended Tutorial: A Complete Guide to Python Dictionaries
Method 4: Longest List in Dict Values Using List Comprehension
You can also get the length of the longest list from the dictionary values by combining a generator expression or list comprehension with the max()
function without key using the following expression: max(len(val) for val in d.values())
Like so:
d = {1: [1, 2, 3], 2: [1, 2], 3: [1], 4: [1, 2, 3, 4]} print(max(len(val) for val in d.values())) # 4
Note that this returns the length of the longest list in the dict values, not the key or the list itself.
A good training effect can be obtained by studying the following tutorial on the topic—feel free to do so!
π Training: Understanding List Comprehension in Python
Method 4: Naive For Loop
A not so Pythonic but still fine approach is to iterate over all key-value pairs in a for
loop, check their length using the len()
function, and compare it against the currently longest list stored in a separate variable. After the termination of the loop, the variable contains the longest list.
Here’s a simple example:
d = {1: [1, 2, 3], 2: [1, 2], 3: [1], 4: [1, 2, 3, 4]} # Initialize variables with dummy values k_max, v_max = -1, [] i = 0 for key,val in d.items(): if len(val) > len(v_max) or i==0: k_max, v_max = key, val i += i print("Longest key and value:", str(k_max) + ',' + str(v_max)) # Longest key and value: 4,[1, 2, 3, 4]
So many lines of code! π I hate it.
π Recommended Tutorial: Python Find Shortest List in Dict
Summary
You have learned about four ways to find the longest list and its length from a Python list of lists (nested list):
- Method 1: max(lst, key=len)
- Method 2: len(max(lst, key=len))
- Method 4: Longest List in Dict Values Using List Comprehension
- Method 4: Naive For Loop
I hope you found the tutorial helpful. If you did, feel free to consider joining our community of likeminded coders—we do have lots of free training material!
π Recommended Tutorial: Python Find Longest List in List