How to Use Generator Expressions in Python Dictionaries

5/5 - (1 vote)

Imagine the following scenario:

You work in law enforcement for the US Department of Labor, finding companies that pay below minimum wage so you can initiate further investigations. Like hungry dogs on the back of a meat truck, your Fair Labor Standards Act (FLSA) officers are already waiting for the list of companies that violated the minimum wage law. Can you give it to them?

Here’s the code from my new book “Python One-Liners“:

companies = {'CoolCompany' : {'Alice' : 33, 'Bob' : 28, 'Frank' : 29},
             'CheapCompany' : {'Ann' : 4, 'Lee' : 9, 'Chrisi' : 7},
             'SosoCompany' : {'Esther' : 38, 'Cole' : 8, 'Paris' : 18}}

illegal = [x for x in companies if any(y<9 for y in companies[x].values())]

Python One-Liner Trick 8 - Evaluate a Condition in a Dictionary of Dictionaries

Try it yourself in our interactive Python shell: