classes vs dicts

Discussion in 'Python' started by Charlie, May 6, 2004.

  1. Charlie

    Charlie Guest

    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.
     
    Charlie, May 6, 2004
    #1
    1. Advertising

  2. Charlie

    Yermat Guest

    Charlie wrote:
    > 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...

    --
    Yermat
     
    Yermat, May 6, 2004
    #2
    1. Advertising

  3. Charlie

    Peter Maas Guest

    Charlie wrote:
    > 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

    --
    -------------------------------------------------------------------
    Peter Maas, M+R Infosysteme, D-52070 Aachen, Hubert-Wienen-Str. 24
    Tel +49-241-93878-0 Fax +49-241-93878-20 eMail
    -------------------------------------------------------------------
     
    Peter Maas, May 6, 2004
    #3
  4. 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


    Charlie wrote:

    > 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.
     
    Richard Taylor, May 6, 2004
    #4
  5. On 6 May 2004 03:12:15 -0700,
    (Charlie) wrote:


    > 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

    --
    Heather Coppersmith
    That's not right; that's not even wrong. -- Wolfgang Pauli
     
    Heather Coppersmith, May 6, 2004
    #5
  6. Charlie

    Isaac To Guest

    >>>>> "Charlie" == Charlie <> writes:

    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.
     
    Isaac To, May 6, 2004
    #6
  7. Isaac To wrote:
    >>>>>>"Charlie" == Charlie <> writes:

    > 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
     
    =?ISO-8859-1?Q?Holger_T=FCrk?=, May 6, 2004
    #7
  8. Charlie

    Terry Reedy Guest

    "Charlie" <> wrote in message
    news:...
    > 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
     
    Terry Reedy, May 6, 2004
    #8
  9. Charlie

    Yermat Guest

    Holger Türk wrote:
    >
    >
    > Isaac To wrote:
    >
    >>>>>>> "Charlie" == Charlie <> writes:

    >>
    >> 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 :

    >>> class Person(object): pass

    ....
    >>> somePerson = Person()
    >>> somePerson.name = "his name"
    >>> somePerson.address = "his address"
    >>>
    >>> somePerson.__dict__

    {'name': 'his name', 'address': 'his address'}

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

    --
    Yermat
     
    Yermat, May 6, 2004
    #9
  10. Charlie

    Peter Otten Guest

    Yermat wrote:

    > 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:

    >>> class Both:

    .... 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
     
    Peter Otten, May 6, 2004
    #10
  11. Charlie

    John Roth Guest

    "Charlie" <> wrote in message
    news:...
    > 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
     
    John Roth, May 6, 2004
    #11
  12. Charlie

    Aahz Guest

    In article <>,
    Heather Coppersmith <> wrote:
    >
    >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.
    --
    Aahz () <*> http://www.pythoncraft.com/

    Adopt A Process -- stop killing all your children!
     
    Aahz, May 6, 2004
    #12
  13. Charlie

    Donn Cave Guest

    In article <>,
    Isaac To <> wrote:

    > >>>>> "Charlie" == Charlie <> writes:

    >
    > 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.


    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,
     
    Donn Cave, May 6, 2004
    #13
  14. Charlie

    Larry Bates Guest

    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=""

    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.

    "Charlie" <> wrote in message
    news:...
    > 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.
     
    Larry Bates, May 6, 2004
    #14
  15. Charlie

    John Hunter Guest

    >>>>> "Charlie" == Charlie <> writes:

    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
     
    John Hunter, May 7, 2004
    #15
  16. Charlie

    Yermat Guest

    Larry Bates wrote:
    > 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 !

    --
    Yermat
     
    Yermat, May 7, 2004
    #16
  17. On 06 May 2004 07:22:05 -0400, Heather Coppersmith <>
    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
     
    Daniel 'Dang' Griffith, May 7, 2004
    #17
  18. Daniel 'Dang' Griffith wrote:

    > On 06 May 2004 07:22:05 -0400, Heather Coppersmith <>
    > 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:

    >>> def new_init(self):

    .... self.a = 1
    .... self.b = 2
    ....
    >>> Foo.__init__ = new_init
    >>> bar = Foo()
    >>> bar.a, bar.b

    (1, 2)
    >>> dir(bar)

    ['__doc__', '__init__', '__module__', 'a', 'b']

    --
    Steven Rumbalski
    news|at|rumbalski|dot|com
     
    Steven Rumbalski, May 7, 2004
    #18
  19. On Fri, 07 May 2004 10:15:11 -0400, Steven Rumbalski
    <> wrote:

    >Daniel 'Dang' Griffith wrote:
    >
    >> On 06 May 2004 07:22:05 -0400, Heather Coppersmith <>
    >> 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:
    >
    >>>> def new_init(self):

    >... self.a = 1
    >... self.b = 2
    >...
    >>>> Foo.__init__ = new_init
    >>>> bar = Foo()
    >>>> bar.a, bar.b

    >(1, 2)
    >>>> dir(bar)

    >['__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
     
    Daniel 'Dang' Griffith, May 10, 2004
    #19
  20. > 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
     
    Josiah Carlson, May 13, 2004
    #20
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Afanasiy

    Add two dicts

    Afanasiy, Aug 29, 2003, in forum: Python
    Replies:
    12
    Views:
    611
    John Roth
    Aug 30, 2003
  2. Jiba

    unicode keys in dicts

    Jiba, Jan 8, 2004, in forum: Python
    Replies:
    2
    Views:
    328
    Peter Hansen
    Jan 8, 2004
  3. Kamilche

    Dicts 5x Faster than Sets

    Kamilche, Jun 9, 2004, in forum: Python
    Replies:
    3
    Views:
    429
  4. =?iso-8859-1?B?R3V5b24gTW9y6WU=?=

    dicts vs classes

    =?iso-8859-1?B?R3V5b24gTW9y6WU=?=, Jul 25, 2006, in forum: Python
    Replies:
    12
    Views:
    523
  5. bruce
    Replies:
    0
    Views:
    277
    bruce
    Jan 10, 2012
Loading...

Share This Page