Dictionary attributes and functions

Michael Chermside mcherm_python at yahoo.com
Fri Mar 9 23:20:28 CET 2001

Well, let me take a shot at it (but bear with me... I'm fairly new at 

 >>> aList = [('a', 123), ('b', 456), ('a', 234)]
 >>> def readAList( aList ):
   """This function reads name-value pairs from a list
   and returns a dictionary whose keys are the names read.
   Each dictionary value is a list of all values which
   paired with that name in the original list."""
   dict = {}
   for (name, value) in aList:
       if dict.has_key(name):
           # it's an existing name
           # it's a new name
           dict[name] = [value]
   return dict

 >>> readAList(aList)
{'b': [456], 'a': [123, 234]}

Of course, you won't be reading a python data structure, so you'll
probably set the variables name and values differently than I do, but
the if statement I've used shows how to add a value to the existing
list if the name is already in the dictionary and create a new, one-element
list if the name is NOT already in the dictionary.

Happy pythoning!

-- Michael Chermside

iddwb wrote:

> I'm looking to read a list of items where their may be duplicates.  I'd
> like to use a dictionary to do this but am way to new to python to know
> fully how to do it.  I'm hoping there is some set of fuctions or
> attributes that can be reference regarding dictionaries... specifically if
> key(a) is already in dictionsary x I'd like to know prior to
> adding.  rather than change the value of key(a) I'd like to add the value
> of key(`a) to the value of key(a) so I end up with
> {keya: [123]}
> on insert of keya againg have something like
> {keya: [123, 234]}
> Any pointers on what to look for in the docs?
> btw, I've been going through Mark Lutz's book on "programming python" but
> I'd like something with a little more langugage reference in it.
> David Bear
> College of Public Programs/ASU

More information about the Python-list mailing list