Data containers: class vs dictionary

Question:

It seems to me that dictionaries are encouraged over defining classes and using classes. When should I use a dictionary over a class and the other way around?

For example if I want to have a dictionary of people and each person has a name and other attributes, two simple ways would be:

  1. Create a dictionary of the people. Each key will be the persons name and the value will be a dictionary of all the attributes that person has.

  2. Create a class Person that contains those attributes and then have a dictionary of Persons, have the name be the key and the Person object the value.

Both solutions seem valid and accomplish the goal, but it still seems as though dictionaries in python would be the way to go. The implementations are different enough that if I wanted to switch back and forth I could run into many changes to go from a class based implementation to a dictionary based implementation and vice versa.

So what am I trading off?

Asked By: Jtello

||

Answers:

Unless you also want to encapsulate behavior with the data, you should use a dictionary. A class is used not only to store data, but also to specify operations performed upon that data.

A dictionary is a great way to get started or to experiment with approaches to solving a problem. They are not a substitute for well-designed classes. Sometimes it’s the right ‘final solution’ and the most efficient way to handle the ‘I only need to carry around some data’ need. I find it useful to start with a dictionary sometimes and usually wind up writing a few functions to provide additional behaviors that I need for the specific case I’m working on. At some point I usually find that it would be neater and cleaner to switch to using a class instead of a dictionary. This is usually determined by the quantity and complexity of behaviors that are required to meet the needs of the situation. Because defining and using a class is so easily done in Python, I find that I switch from "dictionary plus functions" to a class fairly early on. One thing I have discovered is that the ‘quick throw a solution together’ program takes on a life of its own in very many cases — and it’s more productive to have real classes that can be expanded and refactored rather than a large amount of code that (ab)uses dictionaries.

Answered By: Art Swri
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.