Help with Dictionaries and Classes requested please.
Hello, I'm new to this group, I've read through the subject of a lot of the group but can't find anything relevant. Perhaps my question is too basic but I'm still stuck. Classes and Dictionaries. If I have a dictionary, how do I instantiate many instances of a class per dictionary key? Either at run-time or dynamically. Can anyone help me please? Thank you Dominic -- http://mail.python.org/mailman/listinfo/python-list
Re: Help with Dictionaries and Classes requested please.
"special_dragonfly" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> Hello,
> I'm new to this group, I've read through the subject of a lot of the group
> but can't find anything relevant. Perhaps my question is too basic but I'm
> still stuck.
> Classes and Dictionaries.
> If I have a dictionary, how do I instantiate many instances of a class per
> dictionary key? Either at run-time or dynamically.
> Can anyone help me please?
> Thank you
> Dominic
>
>
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.
Dominic
--
http://mail.python.org/mailman/listinfo/python-list
Re: Help with Dictionaries and Classes requested please.
"Bruno Desthuilliers" <[EMAIL PROTECTED]>
wrote in message news:[EMAIL PROTECTED]
> 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
--
http://mail.python.org/mailman/listinfo/python-list
Re: Help with Dictionaries and Classes requested please.
"special_dragonfly" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
>
> "Bruno Desthuilliers" <[EMAIL PROTECTED]>
> wrote in message news:[EMAIL PROTECTED]
>> 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
>
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!
Dominic
--
http://mail.python.org/mailman/listinfo/python-list
Re: Help with Dictionaries and Classes requested please.
"Ben Finney" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> "special_dragonfly" <[EMAIL PROTECTED]> 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
--
http://mail.python.org/mailman/listinfo/python-list
Re: tests
<[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> On Aug 9, 4:04 pm, brad <[EMAIL PROTECTED]> wrote:
>> [EMAIL PROTECTED] wrote:
>> > You should be able to read chunks of each file in binary mode and do a
>> > compare to check for equality. Some kind of loop should do the trick.
>>
>> Why not a simple md5 or sha with the hash library?
>
> Or even:
>
> http://docs.python.org/lib/module-filecmp.html
>
My understanding of reading that is that it only looks at the file names
themselves and not their contents. So whether filename1=filename2 and in the
case of the function below it, whether one directory has files which are in
the other.
Correct me if I'm wrong.
Dom
P.S. md5 or sha hash is what I'd go for, short of doing:
MyFirstFile=file("file1.xls")
MySecondFile=file("file2.xls")
If MyFirstFile==MySecondFile:
print "True"
although this won't tell you where they're different, just that they are...
--
http://mail.python.org/mailman/listinfo/python-list
Help with optimisation
Hello,
I know this might be a little cheeky, and if it is, please say, but I need a
little hand optimising some code. For the simple reason that this is
'company' code and I have no idea what I'm allowed to release and not as the
case may be I've changed anything that could give an indication of the
company - if that makes any sense...
for the code below:
text_buffer is a single record from an XML stream. I can't read in the
entire XML at once because it isn't all available straight away, so I
capture line by line, and when a full message is available I use parseString
under the minidom API.
The SQL version is SQLite. It was recommended to me, and is adequate for the
uses I put it to.
The function doesn't return anything, but it's called often enough and
depending on the optimisation I'll be able to use the same style in other
areas of the program.
previous code:
def CreatePerson(text_buffer):
dom=xml.dom.minidom.parseString(text_buffer)
reflist = dom.getElementsByTagName('Country')
Country = reflist[0].firstChild.nodeValue
reflist = dom.getElementsByTagName('Age')
Age = reflist[0].firstChild.nodeValue
reflist = dom.getElementsByTagName('Surname')
Surname = reflist[0].firstChild.nodeValue
reflist = dom.getElementsByTagName('Forename')
Forename = reflist[0].firstChild.nodeValue
cursor.execute('INSERT INTO Person VALUES(?,?,?)', (Forename + "-" +
Surname, Age, Country))
connection.commit()
I've changed it now to this:
def CreatePerson(text_buffer):
dom=xml.dom.minidom.parseString(text_buffer)
elements=['Country','Age','Surname','Forename']
Values=[]
for element in elements:
reflist=dom.getElementsByTagName(element)
Values.append(reflist[0].firstChild.nodeValue)
# I can get away with the above because I know the structure of the
XML
cursor.execute('INSERT INTO Person
VALUES(?,?,?)',(Forename+"-"+Surname,Age,Country))
connection.commit()
They both seem ugly IMO (read: longer than intuitively necessary), and so I
was wondering whether there was any way to combine Forename and Surname
together within the Values list (think merge cells with the '-' in between)
so I could use the unary(?) operator within the SQL?
I suppose if this is a cheeky request then I won't get any replies.
Thank you for any help
Dominic
--
http://mail.python.org/mailman/listinfo/python-list
Re: about negative polar plots
"Erik Max Francis" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > yadin wrote: > >> hi am doing a polar plot of the radiation pattern of an antenna. >> the polar plots represents the value of the power in dB's and the dB >> go from -40dB to 0dB >> as the angle theta changes from 0 to 2*pi rads >> the polar plot in python goes with positive values >> how can i solve this problem >> rough example >> example: >> power = arange(-40,0,-10) >> theta = arange(0, 2pi,pi/12) >> polar(power,theta) >> title.? >> how can i show the step on the polar plot plot(-40, -30,-20,-10,0) > > What is arange? What is polar? What is plot? You're going to have to > give more information about what you're doing, what you're using to do it, > and where it's giving you unexpected or undesired results if you want help > solving your problem. > > -- > Erik Max Francis && [EMAIL PROTECTED] && http://www.alcyone.com/max/ > San Jose, CA, USA && 37 20 N 121 53 W && AIM, Y!M erikmaxfrancis > So look into my eyes / I won't tell you lies >-- Neneh Cherry I can understand the problem, that when plotting in polar co-ordinates the center of the plot is a value of zero. You're wanting a value of -40 at the center? Is this a fixed quantity? The lines would then extend out to be zero at infinity, presumably by an inverse square law (as it's dB's - unless my physics is wrong). It sounds horrible, but if you know the angle and value, could you not convert to cartesian co-ordinates and plot them? Am I also right in thinking that the example you've given is MATLAB code where you have essentially 2 lists and a function? So power=arange(-40,0,-10) is a list looking like this: [-40,-30,-20,-10,0] theta is a list from 0 to 2pi increasing in increments of pi/12 and the function polar takes the power and theta value and returns... pass (would need to look up the function). http://www.k0gkd.com/fd02.jpg <-- something like this at the end of the day is what is wanted - correct? Now I'm not sure why you can't take your negative value and modulus it with 40 (or whatever value you want at the center). So -40 becomes 40 becomes 0 (the center), -30 becomes 30 becomes 10 (the next band out?) At the end of the day it'll be the labels on the graph you need to change. Tell me if this helps! Dominic -- http://mail.python.org/mailman/listinfo/python-list
Class problems.
Hello,
I'm having problems retrieving data I think I've put into my program. I have
a class and a function. I'm reading in from a personally made text file of
the data needed for the class. The FieldsDictionary needs to be accesable
outside the function, but my problem is this:
the print FieldsDictionary[key].Fieldname (which I should have just created
because of the line above), returns:
AttributeError: 'list' object has no attribute 'Fieldname'
am I just accessing it wrongly?
I was under the impression that Fields Dictionary should contain a key
referencing to a list of instances of the class. i.e.
FieldsDictionary{key:[instance1, instance2, instance 3]}
Is this not what I've programmed?
class FieldClass(object):
def
__init__(self,Fieldname="",Fieldlength=0,Type=["A","S","N"],Location=["D","C","L","H","TBA"]):
self.Fieldname=Fieldname
self.Fieldlength=Fieldlength
self.Type=Type
self.Location=Location
def
EnterDictionary(FieldsDictionary,key,myfile,FIELD_QUANTITY_OFFSET,LINE_START,LINE_END):
data=myfile.readline().strip()
for i in range(int(data[FIELD_QUANTITY_OFFSET:])):
args =myfile.readline().strip()[LINE_START:LINE_END].split(",")
print args
FieldsDictionary.setdefault(key, []).append(FieldClass(*args))
print FieldsDictionary[key].Fieldname
--
http://mail.python.org/mailman/listinfo/python-list
Re: Class problems.
Just ignore this, I was being an idiot...
"special_dragonfly" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> Hello,
> I'm having problems retrieving data I think I've put into my program. I
> have a class and a function. I'm reading in from a personally made text
> file of the data needed for the class. The FieldsDictionary needs to be
> accesable outside the function, but my problem is this:
> the print FieldsDictionary[key].Fieldname (which I should have just
> created because of the line above), returns:
> AttributeError: 'list' object has no attribute 'Fieldname'
> am I just accessing it wrongly?
> I was under the impression that Fields Dictionary should contain a key
> referencing to a list of instances of the class. i.e.
> FieldsDictionary{key:[instance1, instance2, instance 3]}
> Is this not what I've programmed?
>
> class FieldClass(object):
>def
> __init__(self,Fieldname="",Fieldlength=0,Type=["A","S","N"],Location=["D","C","L","H","TBA"]):
>self.Fieldname=Fieldname
>self.Fieldlength=Fieldlength
>self.Type=Type
>self.Location=Location
>
> def
> EnterDictionary(FieldsDictionary,key,myfile,FIELD_QUANTITY_OFFSET,LINE_START,LINE_END):
>data=myfile.readline().strip()
>for i in range(int(data[FIELD_QUANTITY_OFFSET:])):
>args =myfile.readline().strip()[LINE_START:LINE_END].split(",")
>print args
>FieldsDictionary.setdefault(key, []).append(FieldClass(*args))
>print FieldsDictionary[key].Fieldname
>
--
http://mail.python.org/mailman/listinfo/python-list
A problem with Time
Hello, I need to return the date yesterday in the form DDMM. I looked through the modules: time, datetime and calendar but can't find anything that leaps out at me. The problem I'm having is that although I can use time.localtime and get a tuple of the year, month, day and so forth, I don't believe I can just minus 1 from the day, because I don't think it's cyclic, also, I can't see the date being linked in with the month. So is there any way of getting yesterdays date? Thank You Dominic -- http://mail.python.org/mailman/listinfo/python-list
SQLite and coercing to Unicode - please help.
Hello!
First, the problem: the program below falls over with the following error:
TypeError: coercing to Unicode: need string or buffer, NoneType found.
and gives the following line:
"' WHERE secBoardId='"+Values[0]+"'"
My first thought was that Values[0] was containing nothing at all, that
would allow a NoneType to be found, but it has data in that position of the
list - you'll see below.
So I thought that Values[0] was 'losing' its type somewhere, so I checked it
just by having the program print out type(Values[0]), it says it's a
string - also seen below.
So given it's not a NoneType and it's a string, I don't understand why I'm
getting the error. I tried forcing it to a particular type (I think that's
the right word), so I put lines like:
Values[0]=unicode(Values[0]) or
WHERE ... ='"str(Values[0]+"'"
but neither worked.
I've put my code below, I'm sorry it's so long, I've commented the line
where it's falling over.
If it's useful, I am using Python 2.5.1, ElementTree 1.2.6 and pySQLite
2.3.5
If this is a silly mistake ( one where RTFM is a valid response, can you
point me at the place where I can get the answer please?), otherwise any
help is greatly appreciated as I'm out of ideas. :(
Dominic
The output:
At top of function: GBP/PLUS-ofn-GB00B12T7004
Values list contains: ['GBP/PLUS-ofn-GB00B12T7004', u'GBP', u'GB00B12T7004
', u'All Star Minerals plc ', 'ASMO', 'DE', 'PLUS',
u'B12T700', u'', u'A', None, None, None, '00', '0',
'0']
Type of Values[0] is:
The code:
def dealwithSecBRep(text_buffer):
# text_buffer contains a sequential string of xml
Elements=['secBoardId','currencyId','issuerId','secName','secShortName','secClassId',\
'sectorId','isin','issueDate','inheritedState','bidPrice','offerPrice','midPrice',\
'standardMarketSize','openPrice','closePrice']
Values=[]
dom=get_a_document(text_buffer) # this function returns an xml document.
branch=dom.getiterator(Elements[0])
Values.append(GetUniqueId(branch[0])) # Combo of secCode and secBoardId
print "At top of function:",Values[0]
sql=cursor.execute('SELECT*FROM SecB WHERE
secBoardId='+"'"+Values[0]+"'").fetchall()
SQL2=sql
flag=0
if len(sql)>0:
#Prior database exists
try:
branch=dom.getiterator(Elements[1])
Values.append(branch[0].text) # currencyID
except:
value=GetFromDB('currencyCode',text_buffer)
Values.append(value)
try:
branch=dom.getiterator(Elements[2])
Values.append(branch[0].text) # issuerName
except:
value=GetFromDB('issuerName',text_buffer)
Values.append(value)
try:
branch=dom.getiterator(Elements[3])
Values.append(branch[0].text) # Tradable Instrument Name
except:
value=GetFromDB('Tradable Instrument Name',text_buffer)
Values.append(value)
try:
branch=dom.getiterator(Elements[4])
Values.append(branch[0].text) # Tradable Instrument Short Name
except:
value=GetFromDB('Tradable Instrument Short Name',text_buffer)
Values.append(value)
try:
branch=dom.getiterator(Elements[5])
Values.append(branch[0].text) # Tradable Instrument Type
except:
value=GetFromDB('Tradable Instrument Type',text_buffer)
Values.append(value)
try:
branch=dom.getiterator(Elements[6])
Values.append(branch[0].text) # SectorCode
except:
Values.append('PLUS') # SectorCode if one does not naturally
exist
try:
branch=dom.getiterator(Elements[7])
value=str(branch[0].text)
Values.append(value[4:11]) # SEDOL
except:
value=GetFromDB('SEDOL Code',text_buffer)
Values.append(value)
try:
branch=dom.getiterator(Elements[8])
Values.append(branch[0].text) # Date
except:
value=GetFromDB('Tradable Instrument Effective
Date',text_buffer)
Values.append(value)
try:
branch=dom.getiterator(Elements[9])
Values.append(branch[0].text) # inherited State
except:
value=GetFromDB('inheritedState',text_buffer)
Values.append(value)
try:
branch=dom.getiterator(Elements[10])
Values.append(branch[0].text) # bidPrice if available
except:
Values.append("0"*18) # bidPrice if not available
try:
branch=dom.getiterator(Elements[11])
Values.append(branch[0].text) # offerPrice if available
except:
Values.append("0"*18) # offerPrice if not available
try:
branch=dom.getiterator(Elements[12])
Values.append(branch[0].text) # midPrice if available
except:
Va
Re: SQLite and coercing to Unicode - please help.
That helped immensely Steve thank you. You're right, this is my first really
big project ever really, not just in Python.
Just to clarify, my UPDATE statement instead of looking like this:
longstring="UPDATE SecB SET
currencyCode='"+Values[1]+"',issuerName='"+Values[2]
"',instrName='"+Values[3]+\
"',instrShortName='"+Values[4]+"',instrType='"+Values[5]+"',secCode='"+Values[6]+\
"',SEDOL='"+Values[7]+"',Date='"+Values[8]+"',SuspendedState='"+Values[9]+\
"',bidPrice='"+Values[10]+"',offerPrice='"+Values[11]+"',midPrice='"+Values[12]+\
"',standardMarketSize='"+Values[13]+"',openOrClosed='"+Values[14]+\
"' WHERE secBoardId='"+Values[0]+"'"
cursor.execute(longstring)
should instead look more like this:
cursor.execute('UPDATE SecB SET
(?,?,?,?,?,?,?,?,?,?,?,?,?,?)',tuple(Values[1:])) ?
The Elements list was from a time when it looked less pretty than it does
now, where I iterated through it and didn't catch errors at all.
Thank you again for your help and when it's finished and working I'll repost
it online somewhere for ideas on how to optimise it slightly more!
Dominic
"Steve Holden" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> special_dragonfly wrote:
>> Hello!
>> First, the problem: the program below falls over with the following
>> error:
>> TypeError: coercing to Unicode: need string or buffer, NoneType found.
>> and gives the following line:
>> "' WHERE secBoardId='"+Values[0]+"'"
>> My first thought was that Values[0] was containing nothing at all, that
>> would allow a NoneType to be found, but it has data in that position of
>> the list - you'll see below.
>> So I thought that Values[0] was 'losing' its type somewhere, so I checked
>> it just by having the program print out type(Values[0]), it says it's a
>> string - also seen below.
>> So given it's not a NoneType and it's a string, I don't understand why
>> I'm getting the error. I tried forcing it to a particular type (I think
>> that's the right word), so I put lines like:
>> Values[0]=unicode(Values[0]) or
>> WHERE ... ='"str(Values[0]+"'"
>> but neither worked.
>> I've put my code below, I'm sorry it's so long, I've commented the line
>> where it's falling over.
>> If it's useful, I am using Python 2.5.1, ElementTree 1.2.6 and pySQLite
>> 2.3.5
>> If this is a silly mistake ( one where RTFM is a valid response, can you
>> point me at the place where I can get the answer please?), otherwise any
>> help is greatly appreciated as I'm out of ideas. :(
>> Dominic
>>
> OK, the first problem is that you appear to be obsessing about Values[0]
> when there doesn't appear to be any evidence that value in particular is
> causing the problem. The line number being reported is simply that of the
> last line in a single long statement, and the issue could be anywhere in
> that statement. Sorry, you just have to know (or guess) that, it's not a
> particularly admirable feature of Python.
>
> In point of fact it is the None values that are causing the problem:
>
> $ /usr/bin/python
> Python 2.5.1 (r251:54863, May 18 2007, 16:56:43)
> [GCC 3.4.4 (cygming special, gdc 0.12, using dmd 0.125)] on cygwin
> Type "help", "copyright", "credits" or "license" for more information.
> >>> "a string"+None
> Traceback (most recent call last):
> File "", line 1, in
> TypeError: cannot concatenate 'str' and 'NoneType' objects
> >>> u"a string"+None
> Traceback (most recent call last):
> File "", line 1, in
> TypeError: coercing to Unicode: need string or buffer, NoneType found
> >>>
>
> The XML values you are retrieving will be Unicode strings, but you are
> mixing them with plain string values, hence the (somewhat unhelpful) error
> message..
>
> Secondly, you are trying to construct a SQL UPDATE statement yourself,
> instead of parameterising it like you did your INSERT statement. This is
> also usually asking for trouble, and is vulnerable to SQL injection errors
> (use Google if you don't know what they are).
>
> Thirdly, I'
