Python language basics 68: iterating over a dictionary with dictionary comprehension in Python
November 29, 2015 2 Comments
Introduction
In the previous post we looked at a Python language construct called comprehension. We saw that comprehensions are a very concise way of iterating over a collection, applying a function to each element and adding the resulting element to a new collection. All that is declared in a single comprehension statement.
In this post we’ll look at dictionary comprehensions.
Dictionary comprehension
Consider the following dictionary:
sizes = {"XS": "Extra-Small", "S": "Small", "M": "Medium", "L": "Large", "XL": "Extra-Large"}
Here’s how each key and value can be converted into lower case characters:
lower_case_sizes = {size_key.lower():size_name.lower() for size_key, size_name in sizes.items()} print(lower_case_sizes)
{‘l’: ‘large’, ‘xl’: ‘extra-large’, ‘m’: ‘medium’, ‘xs’: ‘extra-small’, ‘s’: ‘small’}
The syntax is somewhat odd but here are the elements:
- The function you’d like to apply on the dictionary key of the new dictionary
- A colon
- The function you’d like to apply on the dictionary value of the new dictionary
- The standard for-each loop for dictionaries
In the above example we use the items() function to get both the key and the value of each item in the iteration. Items() returns a tuple with 2 elements: key and value, and they are saved in the “size_key” and “size_value”, that is we unpack the tuple.
The function applied on the key and value can of course be independent. Here we convert to values into their reversed counterparts:
lower_case_sizes = {size_key.lower():''.join(reversed(size_name)) for size_key, size_name in sizes.items()}
{‘l’: ‘egraL’, ‘xs’: ‘llamS-artxE’, ‘s’: ‘llamS’, ‘xl’: ‘egraL-artxE’, ‘m’: ‘muideM’}
We can also easily build the opposite dictionary where the value becomes the key and vice versa:
lsizes_flipped = {size_name:size_key for size_key, size_name in sizes.items()}
{‘Extra-Large’: ‘XL’, ‘Large’: ‘L’, ‘Extra-Small’: ‘XS’, ‘Small’: ‘S’, ‘Medium’: ‘M’}
In the next post we’ll look at filtering in comprehensions.
Read all Python-related posts on this blog here.
Pingback: Python language basics 68: iterating over a dictionary with dictionary comprehension in Python | Dinesh Ram Kali.
Pingback: Python language basics 69: filtering comprehensions | Dinesh Ram Kali.