472,142 Members | 1,035 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,142 software developers and data experts.

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
Aug 9 '07 #1
23 1529
special_dragonfly wrote:
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?
No, your question is too vague rather than too basic.
What are you trying to do? Please give a concrete example and perhaps some
code that you already have.

Peter
Aug 9 '07 #2
special_dragonfly wrote:
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?
No, your question is too vague rather than too basic.
What are you trying to do? Please give a concrete example and perhaps some
code that you already have.

Peter
Aug 9 '07 #3
special_dragonfly wrote:
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?
No, your question is too vague rather than too basic.
What are you trying to do? Please give a concrete example and perhaps some
code that you already have.

Peter
Aug 9 '07 #4
special_dragonfly wrote:
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?
No, your question is too vague rather than too basic.
What are you trying to do? Please give a concrete example and perhaps some
code that you already have.

Peter
Aug 9 '07 #5
special_dragonfly wrote:
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?
No, your question is too vague rather than too basic.
What are you trying to do? Please give a concrete example and perhaps some
code that you already have.

Peter
Aug 9 '07 #6

"special_dragonfly" <Do*****@PLEASEASK.co.ukwrote in message
news:46***********************@mistral.news.newnet .co.uk...
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
Aug 9 '07 #7

"special_dragonfly" <Do*****@PLEASEASK.co.ukwrote in message
news:46***********************@mistral.news.newnet .co.uk...
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
Aug 9 '07 #8

"special_dragonfly" <Do*****@PLEASEASK.co.ukwrote in message
news:46***********************@mistral.news.newnet .co.uk...
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
Aug 9 '07 #9

"special_dragonfly" <Do*****@PLEASEASK.co.ukwrote in message
news:46***********************@mistral.news.newnet .co.uk...
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
Aug 9 '07 #10

"special_dragonfly" <Do*****@PLEASEASK.co.ukwrote in message
news:46***********************@mistral.news.newnet .co.uk...
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
Aug 9 '07 #11
special_dragonfly wrote:
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.
Since we don't know what exactly of the above you require it's very
hard to give you useful tips. Do you need instance lists, grouped
by keys?

Regards,
Björn

--
BOFH excuse #152:

My pony-tail hit the on/off switch on the power strip.

Aug 9 '07 #12
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
Aug 9 '07 #13

"special_dragonfly" <Do*****@PLEASEASK.co.ukwrote in message
news:46***********************@mistral.news.newnet .co.uk...
>
"Bruno Desthuilliers" <br********************@wtf.websiteburo.oops.com >
wrote in message news:46*********************@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

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


Aug 9 '07 #14
special_dragonfly wrote:
"special_dragonfly" <Do*****@PLEASEASK.co.ukwrote in message
news:46***********************@mistral.news.newnet .co.uk...
>"Bruno Desthuilliers" <br********************@wtf.websiteburo.oops.com >
wrote in message news:46*********************@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


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!
If you mean you would like to store a list of values then you could try
something like

d = {0: MyClass(*data.split(",")}

to create the objects. The .split() method turns the string into a list
of substrings, and the * unary operator turns that list into individual
arguments passed to the __init__() method.

However, your recent question history indicates that you would do well
to study the Python tutorial and other beginner material, as you will
find many valuable hints as to Python best practices which will save you
a lot of time.

Also there is the py*********@python.org list if you are having problems
of a "beginner" nature, where you might get more practical help in your
initial use of the language.

regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
--------------- Asciimercial ------------------
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
----------- Thank You for Reading -------------

Aug 9 '07 #15
On 2007-08-09, special_dragonfly <Do*****@PLEASEASK.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,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
Aug 9 '07 #16
"special_dragonfly" <Do*****@PLEASEASK.co.ukwrites:
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.

--
\ "When we call others dogmatic, what we really object to is |
`\ their holding dogmas that are different from our own." -- |
_o__) Charles Issawi |
Ben Finney
Aug 9 '07 #17
Neil Cerutti a écrit :
On 2007-08-09, special_dragonfly <Do*****@PLEASEASK.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,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. ;)
Hmmm... Neil, I may be wrong but I think you didn't get the point here.
As I understand it, Dominic's problem is that it gets strings like
"Gary,50" and would like to call MyClass initializer this way :
MyClass("Gary", "50")

Aug 9 '07 #18
On 2007-08-09, Bruno Desthuilliers <br********************@wtf.websiteburo.oops.comwr ote:
Neil Cerutti a écrit :
>On 2007-08-09, special_dragonfly <Do*****@PLEASEASK.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,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. ;)

Hmmm... Neil, I may be wrong but I think you didn't get the
point here. As I understand it, Dominic's problem is that it
gets strings like "Gary,50" and would like to call MyClass
initializer this way : MyClass("Gary", "50")
My guess was he doesn't need a class at all, but needed to decide
what he's mapping from->to. It seems far-fetched to me that he
*really* wants a mapping between an index and MyClass objects
containing name and age.

So I tried to cut out the middle-man. Hopefully we can get some
closure on this.

--
Neil Cerutti
Aug 9 '07 #19

"Ben Finney" <bi****************@benfinney.id.auwrote in message
news:87************@benfinney.id.au...
"special_dragonfly" <Do*****@PLEASEASK.co.ukwrites:
>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
Aug 9 '07 #20
Neil Cerutti a écrit :
On 2007-08-09, Bruno Desthuilliers <br********************@wtf.websiteburo.oops.comwr ote:
>Neil Cerutti a écrit :
>>On 2007-08-09, special_dragonfly <Do*****@PLEASEASK.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,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. ;)
Hmmm... Neil, I may be wrong but I think you didn't get the
point here. As I understand it, Dominic's problem is that it
gets strings like "Gary,50" and would like to call MyClass
initializer this way : MyClass("Gary", "50")

My guess was he doesn't need a class at all,
Mmm... That's possible (and if all he has in MyClass are name and age
data attributes, then you're obviously right). But then your answer was
perhaps a bit confusing (at least it confused me...)

Aug 9 '07 #21
special_dragonfly <Do*****@PLEASEASK.co.ukwrote:
if key in FieldsDictionary:
FieldsDictionary[key].append(FieldClass(*line.split(",")))
else:
FieldsDictionary[key]=[FieldClass(*line.split(","))]
These four lines can be replaced by:

FieldsDictionary.setdefault(key, []).append(FieldClass(*line.split(",")))

--
\S -- si***@chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/
"Frankly I have no feelings towards penguins one way or the other"
-- Arthur C. Clarke
her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump
Aug 9 '07 #22
special_dragonfly a écrit :
"Ben Finney" <bi****************@benfinney.id.auwrote in message
news:87************@benfinney.id.au...
>"special_dragonfly" <Do*****@PLEASEASK.co.ukwrites:
>>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(","))]
May I suggest a couple possible improvements ?

First : you're of course free to use any naming convention you like, and
it's obviously better to stay consistent, but the canonical Python
convention is to use all_lower for vars, functions (and methods) and
modules, and MixedCase for classes.

About the code now:

def EnterDictionary(FieldsDictionary,key,data):
for i in range(0,int(data[6:])):

1/ Golden rule : avoid the use of "magic numbers". This one stands true
for any languages !-). The usual solution is to use symbolic constants.
While Python doesn't have real symbolic constant, the convention is to
write them ALL_UPPER.

2/ range() can be used with only one argument, which then will be use as
the upper bound. IOW,
range(0, X)
is the same as
range(X)

line=myfile.readline()

3/ where does this 'myfile' comes from ? (hint : don't use globals when
you can avoid them)
line=line.strip()
line=line[6:-1]

4/ magic numbers again, cf /1. Question : does this 6 has anything to do
with the other one ? What will happen when the file format will change ?

5/ you can do all this in a single line, adding the split() too:
args = myfile.readline().strip()[XXX:-1].split(",")
if key in FieldsDictionary:
FieldsDictionary[key].append(FieldClass(*line.split(",")))
else:
FieldsDictionary[key]=[FieldClass(*line.split(","))]

If you expect key to most of the times be already in FieldsDictionnary,
then a try/except block might be a bit faster. If you expect key to not
be here most of the times, then your solution is right. Note that you
can also use dict.setdefault(key, default):

# probably bad names but I don't have a clue what they should be
DATA_INDEX_OFFSET = 6
LINE_START = 6
LINE_END = -1

def update_fields_dict(fields_dict, key, data, datafile):
for i in range(int(data[DATA_INDEX_OFFSET:])):
args =datafile.readline().strip()[LINE_START:LINE_END].split(",")
fields_dict.setdefault(key, []).append(FieldClass(*args))

Feel free to take or leave what you consider appropriate here. But by
all means avoid magic numbers, except possibly for Q&D throw-away
scripts (and even then...).

HTH
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.
That's usually what happens then, don't worry.
Aug 9 '07 #23
Sion Arrowsmith <si***@chiark.greenend.org.ukwrote:
special_dragonfly <Do*****@PLEASEASK.co.ukwrote:
if key in FieldsDictionary:
FieldsDictionary[key].append(FieldClass(*line.split(",")))
else:
FieldsDictionary[key]=[FieldClass(*line.split(","))]

These four lines can be replaced by:

FieldsDictionary.setdefault(key, []).append(FieldClass(*line.split(",")))
Even better might be to let FieldsDictionary be an instance of
collections.defaultdict(list) [[assuming Python 2.5 is in use]], in
which case the simpler

FieldsDictionary[key].append(FieldClass(*line.split(",")))

will Just Work. setdefault was a valiant attempt at fixing this
problem, but defaultdict is better.
Alex
Aug 11 '07 #24

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

7 posts views Thread by Kerry Neilson | last post: by
8 posts views Thread by Frohnhofer, James | last post: by
3 posts views Thread by Shivram U | last post: by
11 posts views Thread by Alex Maghen | last post: by
1 post views Thread by treelife | last post: by
reply views Thread by special_dragonfly | last post: by
1 post views Thread by Edwin.Madari | last post: by
14 posts views Thread by cnb | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.