Help with Dictionaries and Classes requested please.

Neil Cerutti horpner at yahoo.com
Thu Aug 9 14:42:26 CEST 2007


On 2007-08-09, special_dragonfly <Dominic at PLEASEASK.co.uk> wrote:
> Is there anyway for python to consider the values within a
> string when entering the data into a dictionary. I know that
> isn't very clear so here's an example:
>
> class MyClass(object):
>     def __init__(self,name="",age=""):
>         self.name=name
>         self.age=age
>
> data="Gary,50"
> d={0:[MyClass(data)]}
> data="Adam,25"
> d[0].append(MyClass(data))
>
> The data is coming from a text file working on a line by line
> basis. I've just tried and I'm just getting the full string in
> the first field. That seems logical, now I don't want it to
> though!

That's what happens if you use 0 for the key every time. ;)

If you're trying to map between ages and lists of names, then
you'll want a little helper function to manage the lists for you.

multidict_add(mdict, key, value):
  if key in mdict:
    mdict[key].append(value)
  else:
    mdict[key] = [value]

d = {}
multidict_add(d, 50, "Gary")
multidict_add(d, 50, "Guido")
multidict_add(d, 25, "Adam")

Now you'll get a list of names for every age.

>>> d[50]
["Gary", "Guido"]

You can use the same function to build a mapping from names to
lists of ages.

d = {}
multidict_add(d, "Gary", 50)
multidict_add(d, "Gary", 23)
multidict_add(d, "Adam", 25)

>>> d["Gary"]
[50, 23]

-- 
Neil Cerutti
The choir invites any member of the congregation who enjoys sinning to join
the choir. --Church Bulletin Blooper



More information about the Python-list mailing list