python programming help

Roy Smith roy at
Sun Dec 8 19:23:38 CET 2013

In article <264c1144-5d04-4ad0-aa32-f4e6770d210c at>,
 rafaellasav at wrote:

> i have a dictionary with names and ages for each name. I want to write a 
> function that takes in an age and returns the names of all the people who are 
> that age.
> please help

Homework problem?

In any case, this is a classic example of a real-life problem, and thus 
worth exploring.  The general case is you have a many-to-one mapping and 
you want to find the inverse one-to-many map.

I'm assuming when you say, "a dictionary with names and ages for each 
name", you mean the names are the keys and the ages are the values.  
That would also imply that the names are unique; that's a poor 
assumption for real data sets, but let's assume that's the case here.

So, we're going to take your original dictionary and create a new one 
where the keys are the ages, and the values are lists of names.  That's 
pretty straight forward.  Here's the most brute-force way (which is a 
good place to start):

d2 = {}
for name, age in d1.items():
   if age not in d2:
      d2[age] = []

Work through that code in your head to convince yourself that you 
understand what's going on.

This is such a common pattern, Python has a neat tool to make this 
easier.  It's called a defaultdict.  Bascially, this is a dictionary 
which has built into it the "if key doesn't exist, initialize something" 
logic.  It works like this:

from collections import defaultdict

d2 = defaultdict(list)
for name, age in d1.items():

The "defaultdict(list)" creates one of these and tells it that the 
"initialize something" part should be "create an empty list".  It's 
hugely convenient and used all the time.

More information about the Python-list mailing list