[Tutor] Adding items to dictionaries

Kent Johnson kent37 at tds.net
Thu Jan 26 14:07:10 CET 2006

Jon Moore wrote:
> Hi,
> I have the following dictionary:
> pairs = {"Jon Moore": ["Tony Moore", "Stanley Moore"],
>          "Simon Nightingale": ["John Nightingale", "Alan Nightingale"],
>          "David Willett": ["Bernard Willet", "Robert Willet"],
>          "John Jackson": ["John Jackson", "Peter Jackson"],
>          "James Southey": ["Richard Southey", "Paul Southey"],
>          "Shaun Forsythe": ["William Forsythe", "Angus Forsythe"],
>          "Daniel Geach": ["Mike Geach", "Andy Geach"]}
> Where the names represent a son, father and grandfather.
> I am trying to add a new term and related definitions to the dictionary, 
> but my code does not seem to work:
>         son = raw_input("Please enter the name of the Son: ")
>         if son not in pairs:
>             father = raw_input("Who is the Father?: ")
>             grandfather = raw_input("What is the Grand Father?: ")
>             pairs[son][0] = father
>             pairs[son][1] = grandfather
>             print "\n", son, ",", father, "and" ,grandfather, "have been 
> added."
>         else:
>             print "\nThat Son already exists!"
> The error I get is:
>     pairs[son][0] = father
> KeyError: 'Steven Bates'
>  >>>
> Where am I going wrong?

The problem is, when you say
   pairs[son][0] = father

pairs[son] does not yet exist. This is on the left side of an 
assignment, but it is really an access to pair[son]. It is as if you had 
   temp = pairs[son]
   temp[0] = father

You get a KeyError accessing pairs[son].

The solution is to create a new list for the (father, grandfather) pair, 
and assign that to pairs[son]:

ancestors = [father, grandfather]
pairs[son] = ancestors

You might want to rethink how you are storing the data. (father, 
grandfather) is actually a (son, father) pair so you might want to store 
them as another entry in the dictionary. Also two sons could have the 
same father and grandfather; with your scheme you will store the 
(father, grandfather) pair twice. In general this kind of duplication of 
data is better avoided.

You might also want to Google 'python genealogy'.


More information about the Tutor mailing list