Downside Formulation
💬 Programming Problem: Given a dictionary the place the values are lists of various sizes. Discover and return the shortest checklist!
Right here’s an instance:
d = {1: [1, 2, 3], 2: [1, 2], 3: [1], 4: [1, 2, 3, 4]} # Objective: [1]
Additionally, you’ll learn to clear up a variant of this problem.
💬 Bonus problem: Discover solely the key that’s related to the shortest checklist within the dictionary.
Right here’s an instance:
d = {1: [1, 2, 3], 2: [1, 2], 3: [1], 4: [1, 2, 3, 4]} # Objective: 1
So with out additional ado, let’s get began!
Methodology 1: min(lst, key=len)
Use Python’s built-in min()
perform with a key argument to search out the shortest checklist from the dictionary values. Name min(d.values(), key=len)
to return the shortest checklist in d.values()
utilizing the built-in len()
perform to affiliate the load of every checklist, in order that the shortest checklist would be the minimal.
Right here’s an instance:
d = {1: [1, 2, 3], 2: [1, 2], 3: [1], 4: [1, 2, 3, 4]} print(min(d.values(), key=len)) # [1]
A fantastic one-liner resolution, isn’t it? 🙂 Let’s take a look at a slight variant to examine the key of the shortest checklist as an alternative.
👉 Really useful Tutorial: Python Discover Longest Listing in Dict
Methodology 2: len(min(lst, key=len))
To get the important thing mapping to the shortest checklist worth in a dictionary, use min(d, key=lambda x: len(d[x]))
.
Rationalization: You set the important thing argument of min()
to a lambda perform that maps every dictionary key x
to the size of the related worth obtained with len(d[x])
. This manner, you utilize the size of the mapped values as weights to find out the “minimal”, i.e., the shortest checklist.
💡 Notice: If you name min(d)
Python will routinely substitute it with min(d.keys())
, so it iterates over the keys of the dictionary.
Right here’s an identical instance:
d = {1: [1, 2, 3], 2: [1, 2], 3: [1], 4: [1, 2, 3, 4]} print(min(d, key=lambda x: len(d[x]))) # 1
The important thing with shortest checklist within the dictionary is 4
.
👉 Really useful Tutorial: A Full Information to Python Dictionaries
Methodology 4: Shortest Listing in Dict Values Utilizing Listing Comprehension
You may as well get the size of the shortest checklist from the dictionary values by combining a generator expression or checklist comprehension with the min()
perform with out key utilizing the next expression: min(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(min(len(val) for val in d.values())) # 1
Notice that this returns the size of the shortest checklist within the dict values, not the important thing or the checklist itself.
A very good coaching impact might be obtained by finding out the next tutorial on the subject—be happy to take action!
👉 Coaching: Understanding Listing Comprehension in Python
Methodology 4: Naive For Loop
A not so Pythonic however nonetheless nice strategy is to iterate over all key-value pairs in a for
loop, examine their size utilizing the len()
perform, and evaluate it towards the at the moment shortest checklist saved in a separate variable. After the termination of the loop, the variable incorporates the shortest checklist.
Right here’s a easy instance:
d = {1: [1, 2, 3], 2: [1, 2], 3: [1], 4: [1, 2, 3, 4]} # Initialize variables with dummy values k_min, v_min = -1, [] i = 0 for key,val in d.objects(): if len(val) < len(v_min) or i==0: k_min, v_min = key, val i += i print("Shortest key and worth:", str(k_min) + ',' + str(v_min)) # Shortest key and worth: 3,[1]
So many strains of code! 😅 I hate it.
Abstract
You have got discovered about 4 methods to search out the shortest checklist and its size from a Python checklist of lists (nested checklist):
I hope you discovered the tutorial useful. When you did, be happy to contemplate becoming a member of our neighborhood of likeminded coders—we do have plenty of free coaching materials!
👉 Really useful Tutorial: Python Discover Longest Listing in Listing
Whereas working as a researcher in distributed methods, Dr. Christian Mayer discovered his love for instructing laptop science college students.
To assist college students attain larger ranges of Python success, he based the programming schooling web site Finxter.com. He’s writer of the favored programming e-book Python One-Liners (NoStarch 2020), coauthor of the Espresso Break Python sequence of self-published books, laptop science fanatic, freelancer, and proprietor of one of many prime 10 largest Python blogs worldwide.
His passions are writing, studying, and coding. However his biggest ardour is to serve aspiring coders by means of Finxter and assist them to spice up their abilities. You may be a part of his free electronic mail academy right here.