Help with Dictionaries and Classes requested please.
special_dragonfly
Dominic at PLEASEASK.co.uk
Thu Aug 9 09:59:07 EDT 2007
"Ben Finney" <bignose+hates-spam at benfinney.id.au> wrote in message
news:87ejic6dkw.fsf at benfinney.id.au...
> "special_dragonfly" <Dominic at PLEASEASK.co.uk> writes:
>
>> I've managed to solve the problem, I really was just being a
>> dunce.
>
> Doubtful; but at this stage we can't tell, because we still don't know
> what it is you're actually trying to *do*.
>
>> Here's how incase anyone is wondering:
>>
>> class MyClass:
>> def __init__(self):
>> name=""
>> dict={}
>> dict[0]=[]
>> dict[0].append(MyClass())
>> dict[0][0].name="Hello"
>> print dict[0][0].name
>
> It's not clear why you are using the value 0 for a dictionary key
> here; nor why you're assigning an attribute to an object after
> creating the object. Neither of them are errors, but without context
> it's hard to know what advice to give.
>
The 0 for a key is just an example. The code I actually have would be just
as meaningful at the end of the day. I could have changed MyClass for
class Animals(object):
def __init__(self, name="", type="", age=""):
self.name=name
self.type=type
self.age=age
dict={'Mouse':[Animals('George','long eared',20)]}
dict['Mouse'].append(Animals('Benny','hairy',30))
dict['Cat']=[Animals('Inigo Montoya','spanish',10)]
and Neil, Bruno has the right idea of what I was trying to do. However, your
code came in handy still as I used your code elsewhere.see below.
def EnterDictionary(FieldsDictionary,key,data):
for i in range(0,int(data[6:])):
line=myfile.readline()
line=line.strip()
line=line[6:-1]
if key in FieldsDictionary:
FieldsDictionary[key].append(FieldClass(*line.split(",")))
else:
FieldsDictionary[key]=[FieldClass(*line.split(","))]
I'd like to thank you all for your patience with me whilst I've asked some
really beginner-like questions. I hope I haven't annoyed you all too much...
In future I would ask however, if it's a really stupid question and you feel
that the answer can be found either by searching google (because in some
cases I don't know what to search for), or in one of the O'reilly books,
just say. In either case, if you could refer me to the search term to use or
the book to read I'd be grateful.
Dominic
More information about the Python-list
mailing list