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:
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.
Create a class Person
that contains those attributes and then have a dictionary of Person
s, 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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With