Help with Dictionaries and Classes requested please.
special_dragonfly
Dominic at PLEASEASK.co.uk
Thu Aug 9 07:15:21 EDT 2007
"Bruno Desthuilliers" <bruno.42.desthuilliers at wtf.websiteburo.oops.com>
wrote in message news:46baf183$0$433$426a74cc at news.free.fr...
> special_dragonfly a écrit :
> (snip)
>> I've managed to solve the problem, I really was just being a dunce.
>> 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
>>
>> I'm sorry if I've wasted anyones time, although if there's a better way
>> of doing the above I'd still be interested to know.
>
> # unless you need pre 2.3.x compat, better to use newstyle classes
> class MyClass(object):
> # use the initializer to initialize your instance
> def __init__(self, name=''):
> # the use of 'self' is mandatory, else you only have a local var
> self.name = name
>
> # don't use builtin names as identifiers - unless you really want to
> # shadow the builtins
> d = {0:[MyClass('hello')}
> d[0].append(MyClass('goodbye'))
> d.setdefault(1, []).append(MyClass('Yo'))
> print d
>
> HTH
Hello
To answer first Bjoern:
I have a dictionary and a class. The dictionary needs to be filled with
multiple instances of the class, with multiple instances per key. Currently
a lot of the dictionaries that are going into the program are hard coded
because they're just 1:1 mappings, in this case though it was a many:1
mapping and so I got a little stumped. I couldn't hard coded the mappings,
so I then needed to find a way of doing it dynamically. I'm now reading data
from a file containing the data for the class, and am now able to put that
data into a dictionary.
I'm quite new to programming large things, and previous experience has only
been in C and C++, so I'm also trying to get an idea of good programming
practises. Other people are going to need to use this program, I need it to
be... correct... should someone need to alter it. So loads of documentation,
and meaningful variable names, but it's also experience that I'm lacking. Is
there a better way of doing such-and-such, or is it sensible to do it this
way....?
The code above does what I need, thank you Bruno. I can understand that my
code is right there next to useless when trying to describe what I need to
do.
Were I doing this in C, I would be creating a 2D array of structures, at
least... I believe that's how it would look.
Thank you for your help, all of you.
Dominic
More information about the Python-list
mailing list