Re: Help with Dictionaries and Classes requested please.
On 2007-08-09, special_dragonf ly <Dominic@PLEASE ASK.co.ukwrote:
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(m dict, 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.
["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)
[50, 23]
--
Neil Cerutti
The choir invites any member of the congregation who enjoys sinning to join
the choir. --Church Bulletin Blooper
On 2007-08-09, special_dragonf ly <Dominic@PLEASE ASK.co.ukwrote:
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,n ame="",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!
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,n ame="",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!
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(m dict, 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]
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"]
--
Neil Cerutti
The choir invites any member of the congregation who enjoys sinning to join
the choir. --Church Bulletin Blooper
Comment