[Tutor] need a hint

Alan Gauld alan.gauld at btinternet.com
Mon Dec 2 16:03:11 CET 2013


On 02/12/13 11:03, Wolfgang Maier wrote:

> ... and since you want to be able to resolve ambiguous last names based on
> first names, you will have to store not just the states, but also the first
> names.
> You can do so by turning the entries in senateInfo from a list of strings
> (states) into a list of tuples (first name, state) like this:
>
>      senateInfo[lastName] = [(firstName, state)]
>
> or for pre-existing entries:
>
>      senateInfo[lastName].append((firstName, state))

This results in a mixed set of values for your dictionary. Some will be 
simple strings (or tuples), others lists of tuples. You might want to 
consider standardising on a list for all even if some only have a single 
value.

This should simplify the code needed to extract the data later.

You can also use the dictionary get() method to return an empty
list if no entry exists yet so your entry code looks like

info[lastName] = info.get(lastName,[]).append((firstName, state))

And your retrieval code can use the same approach:

# get() returns a list of 0,1 or multiple tuples
for firstName,state in info.get(lastName, []):
     # process the tuple

hth
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos



More information about the Tutor mailing list