classes vs dicts

C

Charlie

Greetings,

I am pretty new to Python and like it very much, but there is one
thing I can't figure out and I couldn't really find anything in the
docs that addresses this.

Say I want to write an address book program, what is the best way to
define a person (and the like): create a class (as I would do in Java)
or use a dictionary?
I guess using dictionaries is fastest and easiest, but is this
recommended?

Thanx for any help.
 
Y

Yermat

Charlie said:
Greetings,

I am pretty new to Python and like it very much, but there is one
thing I can't figure out and I couldn't really find anything in the
docs that addresses this.

Say I want to write an address book program, what is the best way to
define a person (and the like): create a class (as I would do in Java)
or use a dictionary?
I guess using dictionaries is fastest and easiest, but is this
recommended?

Thanx for any help.

create a class !

You're wrong when you're saying that dictionaries is fastest because
class use dictionaries to find attributes so that the same ! But class
is nicer to read and manage...
 
P

Peter Maas

Charlie said:
Say I want to write an address book program, what is the best way to
define a person (and the like): create a class (as I would do in Java)
or use a dictionary?

Use a class to model address data, advantage is that you can define
methods operating on address data, subclass address etc.

A dictionary gives you fast access to data by key. You could create
a dictionary of adresses that maps keys to addresses.

You can store such a dictionary with shelve module functions. Easy
to handle and sufficient if you don't need multi user access, an
SQL interface or have huge amount of data.

Mit freundlichen Gruessen,

Peter Maas
 
R

Richard Taylor

Charlie

Personally I would almost always use a class.

A class is much more flexible and you may want to add some methods to you
people.

A class also allows you to put format checking into the constructor, define
getters/setters etc.

For example:

class Person(object):
def __init__(self,name="unknown"):
self.name = name

# If you like setters and getters.
def getName(self): return self.__name
def setName(self, value): self.__name = value
def delName(self): del self.__name
name = property(getName, setName, delName, "I'm the 'Name' property.")

Richard
 
H

Heather Coppersmith

On 6 May 2004 03:12:15 -0700,
Say I want to write an address book program, what is the best
way to define a person (and the like): create a class (as I
would do in Java) or use a dictionary?
I guess using dictionaries is fastest and easiest, but is this
recommended?

In the end (and in the implementation), classes are just syntactic
sugar for dictionaries.

object.attribute is equiv. to dictionary[ 'key' ]

"Faster" is probably not applicable unless you're doing thousands
of lookups (designing and coding times should be about the same).
"Easiest" is a matter of personal taste.

HTH,
Heather
 
I

Isaac To

Charlie> Greetings, I am pretty new to Python and like it very much, but
Charlie> there is one thing I can't figure out and I couldn't really
Charlie> find anything in the docs that addresses this.

Charlie> Say I want to write an address book program, what is the best
Charlie> way to define a person (and the like): create a class (as I
Charlie> would do in Java) or use a dictionary? I guess using
Charlie> dictionaries is fastest and easiest, but is this recommended?

I read the answers already in the list, which are rather unidirectional: all
advocate for classes. But I'm unconvinced. I still believe that there is
no clear-cut winner, and what you should do dopend on how you view the
person.

If you want to associate actions to the person, say associate two persons in
some way; and you want to create various types of persons (subclass it) such
that each of them have different behaviour, then the extra complexity added
by representing the person as a class will definitely pay off.

But, on the other hand, if your application simply treat the person as some
data, turning every access of the person into a getter or a setter or even a
combination will only make code more clumsy and harder to write.

Python is about making the complexity where it worth. If you cannot see
that a class will help, the safe choice is to do it with a dict. Later, if
you find that a class would really help, switch to use a class, hopefully by
then you already has a clear idea about why you want a class. In that way
you won't create a lot of useless class functions at the beginning when the
actual use of the class is unclear. And you won't waste a lot of time doing
design and later find that your application can be written in a completely
different, more elegant way.

Regards,
Isaac.
 
?

=?ISO-8859-1?Q?Holger_T=FCrk?=

Isaac said:
Charlie> Greetings, I am pretty new to Python and like it very much, but
Charlie> there is one thing I can't figure out and I couldn't really
Charlie> find anything in the docs that addresses this.

Charlie> Say I want to write an address book program, what is the best
Charlie> way to define a person (and the like): create a class (as I
Charlie> would do in Java) or use a dictionary? I guess using
Charlie> dictionaries is fastest and easiest, but is this recommended?


Python is about making the complexity where it worth. If you cannot see
that a class will help, the safe choice is to do it with a dict. Later, if


I don't think so. If you don't want to define set... and get ...
methods, you can still misuse a class in this way:


class Person (object): pass

somePerson = Person ()
somePerson.name = "his name"
somePerson.address = "her address"


instead of


somePerson = {}
somePerson ["name"] = "his name"
somePerson ["address"] = "her address"


The first alternative is easier to read and even safer:
If you need to extend the capabilities of the class, you can
still redefine the behaviour of the data fields using
descriptors.

Greetings,

Holger
 
T

Terry Reedy

Charlie said:
Greetings,

I am pretty new to Python and like it very much, but there is one
thing I can't figure out and I couldn't really find anything in the
docs that addresses this.

Say I want to write an address book program, what is the best way to
define a person (and the like): create a class (as I would do in Java)
or use a dictionary?

You can represent a person by a tuple, dictionary, or class instance. All
three ways of representing records are used in various places in the
standard library. The 'best way' depends on the specifics of the
situation.

You can represent a collection of persons -- an address book -- by a list,
dictionary, list + index dictionary, dictionary as person class attribute,
class derived from dict, or class with dict as per instance attribute.
Same comment as to 'best'.
I guess using dictionaries is fastest and easiest, but is this
recommended?

I would concentrate on easiest to program to get desired functionality.

Terry J. Reedy
 
Y

Yermat

Holger said:
Isaac said:
Charlie> Greetings, I am pretty new to Python and like it very
much, but
Charlie> there is one thing I can't figure out and I couldn't really
Charlie> find anything in the docs that addresses this.

Charlie> Say I want to write an address book program, what is the
best
Charlie> way to define a person (and the like): create a class (as I
Charlie> would do in Java) or use a dictionary? I guess using
Charlie> dictionaries is fastest and easiest, but is this
recommended?


Python is about making the complexity where it worth. If you cannot see
that a class will help, the safe choice is to do it with a dict.
Later, if



I don't think so. If you don't want to define set... and get ...
methods, you can still misuse a class in this way:


class Person (object): pass

somePerson = Person ()
somePerson.name = "his name"
somePerson.address = "her address"


instead of


somePerson = {}
somePerson ["name"] = "his name"
somePerson ["address"] = "her address"


The first alternative is easier to read and even safer:
If you need to extend the capabilities of the class, you can
still redefine the behaviour of the data fields using
descriptors.

Greetings,

Holger

And do remember that actually, class ARE (kind of) dictionnary :
{'name': 'his name', 'address': 'his address'}

So the real question is what do you prefer to type : somePerson.name or
somePerson["name"] ?

--
Yermat
 
P

Peter Otten

Yermat said:
So the real question is what do you prefer to type : somePerson.name or
somePerson["name"] ?

And if you [OP] really cannot make up your mind:
.... def __getitem__(self, key):
.... return self.__dict__[key]
.... def __setitem__(self, key, value):
.... self.__dict__[key] = value
....
b = Both()
b["name"] = "won't tell"
b.name "won't tell"
b.address = "in the middle of nowhere"
b["address"] 'in the middle of nowhere'
b["this is nasty"] = "now what?"

After all a class is just syntactic sugar for a dictionary and a dictionary
is just a class, which is...

:)
Peter
 
J

John Roth

Charlie said:
Greetings,

I am pretty new to Python and like it very much, but there is one
thing I can't figure out and I couldn't really find anything in the
docs that addresses this.

Say I want to write an address book program, what is the best way to
define a person (and the like): create a class (as I would do in Java)
or use a dictionary?
I guess using dictionaries is fastest and easiest, but is this
recommended?

Thanx for any help.

As a number of people have said, there is no "right" answer.
My take on it is to ask how the rest of the program is organized.
If the rest of the program is object oriented, I'd use a class;
if it's procedurally oriented, I'd use a dictionary. In other words,
I'd try to keep some conceptual integrity with the program as
a whole.

John Roth
 
A

Aahz

In the end (and in the implementation), classes are just syntactic
sugar for dictionaries.

object.attribute is equiv. to dictionary[ 'key' ]

Saying that masks some critically important machinery that classes
provide. For example::

class A:
x = 'spam'

class B(A):
pass

z = B()
print z.x
print z.__dict__['x']

That machinery can make classes quite a bit slower in some cases, though
you're correct that it's more important to focus on the functional needs
than performance.
 
D

Donn Cave

Charlie> Greetings, I am pretty new to Python and like it very much, but
Charlie> there is one thing I can't figure out and I couldn't really
Charlie> find anything in the docs that addresses this.

Charlie> Say I want to write an address book program, what is the best
Charlie> way to define a person (and the like): create a class (as I
Charlie> would do in Java) or use a dictionary? I guess using
Charlie> dictionaries is fastest and easiest, but is this recommended?

I read the answers already in the list, which are rather unidirectional: all
advocate for classes. But I'm unconvinced. I still believe that there is
no clear-cut winner, and what you should do dopend on how you view the
person.

If you want to associate actions to the person, say associate two persons in
some way; and you want to create various types of persons (subclass it) such
that each of them have different behaviour, then the extra complexity added
by representing the person as a class will definitely pay off.

But, on the other hand, if your application simply treat the person as some
data, turning every access of the person into a getter or a setter or even a
combination will only make code more clumsy and harder to write.[/QUOTE]

I agree - for plain data, use a plain data structure. One advantage,
beside just the obviousness of it all, is that your data structure will
support data structure operations, like iteration for example.

Donn Cave, (e-mail address removed)
 
L

Larry Bates

You will probably want a dictionary with keys to
find people with classes stored to hold the information
about the people. That way you can extend the class
easily without disrupting your data structures.

class person:
def __init__(self, lastname, firstname, initial):
self.lastname=lastname
self.firstname=firstname
self.initial=initial
return

#
# Main Program
#
all_people={}

all_people['LarryABates']=person('Larry','Bates','A')
all_people['SomeOPerson']=person('Some','Person','O')

Then you can do things like:

all_people['LarryABates'].telephone="2055551234"
all_people['LarryABates'].faxphone="2055551235"

or

entry=all_people['LarryABates']

print entry.lastname
print entry.firstname
print entry.initial
print entry.telephone
entry.emailaddress="(e-mail address removed)"

I was new to OOP and it took me the longest to understand
that I can store classes just like any other data value.

HTH,
Larry Bates
Syscon, Inc.
 
J

John Hunter

Charlie> Greetings, I am pretty new to Python and like it very
Charlie> much, but there is one thing I can't figure out and I
Charlie> couldn't really find anything in the docs that addresses
Charlie> this.

Charlie> Say I want to write an address book program, what is the
Charlie> best way to define a person (and the like): create a
Charlie> class (as I would do in Java) or use a dictionary? I
Charlie> guess using dictionaries is fastest and easiest, but is
Charlie> this recommended?

For simple data with just a few fields, a tuple may be all you need

people = (
('John', 'D', 'Hunter', 36),
('Miriam', 'A', 'Sierig', 33),
('Rahel', 'S', 'Hunter', 6),
)

for first, middle, last, age in people:
print '%s %s %s is %d years old' % (first, middle, last, age)

When you use named tuple unpacking, ie,

first, middle, last, age = row

rather than indexing operations, ie row[0], I find using tuples can be
as readable as classes or dicts. Again only for simple data
structures...

John Hunter
 
Y

Yermat

Larry said:
You will probably want a dictionary with keys to
find people with classes stored to hold the information
about the people. That way you can extend the class
easily without disrupting your data structures.

class person:
def __init__(self, lastname, firstname, initial):
self.lastname=lastname
self.firstname=firstname
self.initial=initial
return

#
# Main Program
#
all_people={}

all_people['LarryABates']=person('Larry','Bates','A')
all_people['SomeOPerson']=person('Some','Person','O')
> [...]

Your all_people should also be a class then it can simplify stuff !

class PersonCollection:
def __init__(self):
self.all_people = {}

def add(self, person):
key = '%s%s%s' % (person.lastname,
person.initial,
person.firstname)
self.all_people[key] = person

def __getitem__(self, key):
return self.all_people[key]

then you will just do :

all_people = PersonCollection()
all_people.add(person('Larry','Bates','A'))
all_people.add(person('Some','Person','O'))

But you will still be able to do :

all_people['SomeOPerson'].phone = "+44 3 54 65 85 96"

If Objet-Oriented languages were invented, there was a reason !
 
D

Daniel 'Dang' Griffith

On 06 May 2004 07:22:05 -0400, Heather Coppersmith <[email protected]>
wrote:
....
In the end (and in the implementation), classes are just syntactic
sugar for dictionaries.

object.attribute is equiv. to dictionary[ 'key' ]

I think you're overgeneralizing, or I'm reading overgenerality into
your response. I assume you mean that manipulating an instance of a
class attribute is syntactic sugar for manipulating a single
dictionary entry?

You can't arbitrarily add or remove attributes to an instance of a
class (without using "magic", which kinda puts a major sour in the
syntactic sugar!). Classes are not syntactic sugar for dictionaries.
--dang
 
S

Steven Rumbalski

Daniel said:
On 06 May 2004 07:22:05 -0400, Heather Coppersmith <[email protected]>
wrote:
...
In the end (and in the implementation), classes are just syntactic
sugar for dictionaries.

object.attribute is equiv. to dictionary[ 'key' ]

I think you're overgeneralizing, or I'm reading overgenerality into
your response. I assume you mean that manipulating an instance of a
class attribute is syntactic sugar for manipulating a single
dictionary entry?

You can't arbitrarily add or remove attributes to an instance of a
class (without using "magic", which kinda puts a major sour in the
syntactic sugar!). Classes are not syntactic sugar for dictionaries.
--dang
.... def __init__(self):
.... self.x = 'x'
.... self.y = 'y'
....
foo = Foo()
foo.x, foo.y ('x', 'y')
dir(foo) ['__doc__', '__init__', '__module__', 'x', 'y']
foo.z = 'zeeeeee'
del foo.x
foo.y, foo.z ('y', 'zeeeeee')
dir(foo)
['__doc__', '__init__', '__module__', 'y', 'z']


I'm not sure what you mean by magic. I just used basic python to
"arbitrarily add or remove attributes to an instance".

You can even muck around with classes:
.... self.a = 1
.... self.b = 2
....['__doc__', '__init__', '__module__', 'a', 'b']
 
D

Daniel 'Dang' Griffith

Daniel said:
On 06 May 2004 07:22:05 -0400, Heather Coppersmith <[email protected]>
wrote:
...
In the end (and in the implementation), classes are just syntactic
sugar for dictionaries.

object.attribute is equiv. to dictionary[ 'key' ]

I think you're overgeneralizing, or I'm reading overgenerality into
your response. I assume you mean that manipulating an instance of a
class attribute is syntactic sugar for manipulating a single
dictionary entry?

You can't arbitrarily add or remove attributes to an instance of a
class (without using "magic", which kinda puts a major sour in the
syntactic sugar!). Classes are not syntactic sugar for dictionaries.
--dang
class Foo:
... def __init__(self):
... self.x = 'x'
... self.y = 'y'
...
foo = Foo()
foo.x, foo.y ('x', 'y')
dir(foo) ['__doc__', '__init__', '__module__', 'x', 'y']
foo.z = 'zeeeeee'
del foo.x
foo.y, foo.z ('y', 'zeeeeee')
dir(foo)
['__doc__', '__init__', '__module__', 'y', 'z']


I'm not sure what you mean by magic. I just used basic python to
"arbitrarily add or remove attributes to an instance".

You can even muck around with classes:
... self.a = 1
... self.b = 2
...['__doc__', '__init__', '__module__', 'a', 'b']

Yes, you're right. I mis-spoke what I meant. Maybe this is closer,
"You can't add or remove arbitrary attributes to an instance of a
class... without magic." What I mean is that with a dictionary, the
keys can come from external/arbitrary data and be added to the
dictionary with a simple assignment:

d = dict()
k, v = raw_input(), raw_input()
d[k] = v
w = d[k]

You can't do that to classes or instances without some kind of magic.

class Foo: pass
foo = Foo()
k, v = raw_input(), raw_input()
setattr(foo, k, v)
w = getattr(foo, k)

Maybe its just me, but I consider getattr/setattr magic (although in
this simple example, they don't appear too magical, so maybe others
wouldn't consider it so).

Still, I think it is an overgeneralization to say that classes are
just syntactic sugar for dictionaries.

--dang
 
J

Josiah Carlson

Still, I think it is an overgeneralization to say that classes are
just syntactic sugar for dictionaries.

How about this; classes are syntactic sugar for handling object
namespaces. Since object namespaces in Python are generally handled
with dictionaries, classes are therefore syntactic sugar for dictionaries.

Before I read the tutorial on classes when I was learning Python that
fateful afternoon years ago, I used dictionaries as the equivalent of
instance namespaces. For about 20 minutes it bothered me that I had to
use quotation marks to get and set attributes, until I read the class
portion of the tutorial and said "ah-hah, classes embed dictionaries as
namespaces, perfect", or something like that.

- Josiah
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,534
Members
45,007
Latest member
obedient dusk

Latest Threads

Top