This article addresses two problems:
- Given is a dictionary and a single key. How to get the length of the value associated with the key in the dictionary?
- Given is a dictionary. How to get the total length, summing over the length of all values in the dictionary?
Let’s dive into these two problems and find the most Pythonic solution for both! Methods 1 and 2 solve the first problem. Methods 3 and 4 solve the second problem.
Method 1: Length of Single Dictionary Value
Given the following dictionary that maps the age (int
) to a list of persons (str
) with that particular age:
age = {17: ['alice', 'bob'], 21: ['carl', 'frank', 'pete']}
You want to obtain the length of the value associated with key 21
. The value associated with the key 21
is the list ['carl', 'frank', 'pete']
that has length 3
(three elements).
To obtain the length of a dictionary value associated with a given key, access the value using the expression dict[key]
and pass it into the length function like so: len(dict[key])
. The return value is the length of the iterable associated with this specific key.
Here’s how you’d accomplish this for our given example:
age = {17: ['alice', 'bob'], 21: ['carl', 'frank', 'pete']} # Length of value associated with key 17: res = len(age[17]) print(res) # 3 # Length of value associated with key 21: res = len(age[21]) print(res) # 2
This approach is not perfect though.
Method 2: Length of Possibly Non-Existing and Non-Iterable Dictionary Value
What if you want to get the length of the value but you’re not sure whether the value is an iterable in the first place?
Have a look at this example:
age = {17: ['alice', 'bob'], 21: ['carl', 'frank', 'pete'], 23: None} # Length of value associated with key 23: res = len(age[23]) print(res)
This leads to the following TypeError: object of type 'NoneType' has no len()
:
Traceback (most recent call last): File "C:\...\code.py", line 7, in <module> res = len(age[23]) TypeError: object of type 'NoneType' has no len()
Here’s the code function that fixes this:
def get_length(d, k): ''' Return length of value associated with key k in dict d''' if k in d: v = d[k] if isinstance(v, (str,list)): return len(v) return 1 return 0
You start by checking if the key is in the dictionary using the membership operator in
.
If the key is in the dictionary, you need to make sure that the associated value is a string or list so you can check the len()
function. You use the isinstance()
built-in function to accomplish this.
π‘ Note: You can check for even more data types by extending the second tuple argument of the isinstance()
function. For example, to also allow for sets, use the (str,list,set)
tuple as the second argument.
Now, you have the following three cases in the function:
- If the key is in the dictionary and the value is an iterable, you return the length of the iterable.
- If the key is in the dictionary and the value is not an iterable, you return the fixed length of 1.
- If the key is not in the dictionary, you return 0 because the length of a non-existing value is 0.
Okay, let’s learn how to to get the total (summed) length of all values in the dictionary next!
Method 3: Total Length of All Dictionary Values
Next, we assume that everything is nice and cozy and all dictionary values are iterables that we can pass into the len()
function. In this case, the solution is simple: dictionary comprehension.
To get the summed length of all dictionary values, you can use the dictionary comprehension statement:
sum(len(v) for v in d.values())
This iterates over all dictionary values using the dict.values()
method and calculates the length of each dictionary element. The resulting iterable is passed into the built-in sum()
function.
The return value is the summed length of all dictionary values.
Here’s an example:
age = {17: ['alice', 'bob'], 21: ['carl', 'frank', 'pete'], 23: ['ann']} def get_length(d): ''' Return length of all dict values''' return sum(len(v) for k, v in d.items()) res = get_length(age) print(res) # 6
However, this is not sufficient if at least one dictionary value is not an iterable.
Method 4: Total Length of All Dictionary Values with Non-Iterable Values
To get the total (summed) length of all dictionary values if one or more values may be non-iterable, use the following effective one-liner:
sum(len(v) if isinstance(v, (list,str)) else 1 for v in d.values())
This one-liner is similar to the above method:
- The dictionary comprehension goes over all values in the dictionary.
- For each value
v
, it uses the ternary expression with the conditionisinstance(v, (list, str))
to check if the value is an iterable of type list or string.- If yes, you can return the result of
len(v)
. - If not, you return
1
because it’s a non-iterable that’s counted as a single value.
- If yes, you can return the result of
Here’s the full code example:
age = {17: ['alice', 'bob'], 21: ['carl', 'frank', 'pete'], 23: None} def get_length(d): ''' Return length of all dict values''' return sum(len(v) if isinstance(v, (list,str)) else 1 for v in d.values()) res = get_length(age) print(res) # 6
This is the most Pythonic solution to this problem in my opinion! But I’m biased—I love one-liners so much so that I’ve written a book about it…
Python One-Liners Book: Master the Single Line First!
Python programmers will improve their computer science skills with these useful one-liners.
Python One-Liners will teach you how to read and write “one-liners”: concise statements of useful functionality packed into a single line of code. You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.
The book’s five chapters cover (1) tips and tricks, (2) regular expressions, (3) machine learning, (4) core data science topics, and (5) useful algorithms.
Detailed explanations of one-liners introduce key computer science concepts and boost your coding and analytical skills. You’ll learn about advanced Python features such as list comprehension, slicing, lambda functions, regular expressions, map and reduce functions, and slice assignments.
You’ll also learn how to:
- Leverage data structures to solve real-world problems, like using Boolean indexing to find cities with above-average pollution
- Use NumPy basics such as array, shape, axis, type, broadcasting, advanced indexing, slicing, sorting, searching, aggregating, and statistics
- Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning
- Create more advanced regular expressions using grouping and named groups, negative lookaheads, escaped characters, whitespaces, character sets (and negative characters sets), and greedy/nongreedy operators
- Understand a wide range of computer science topics, including anagrams, palindromes, supersets, permutations, factorials, prime numbers, Fibonacci numbers, obfuscation, searching, and algorithmic sorting
By the end of the book, you’ll know how to write Python at its most refined, and create concise, beautiful pieces of “Python art” in merely a single line.