A dict
can use any hashable value as a key, while a class
instance needs to have strings that are legal identifiers as its "keys". So you can bundle together arbitrary data in a dict
.
It's pretty common to use a trivial class as a more-convenient dict
when your key values will all be valid identifier strings anyway:
class Box:
pass
x = Box()
x.a = 0
x.b = 1
d = {}
d["a"] = 0 # "x.a" is easier to type than this
d["b"] = 1
print("Current value for 'a' is: {}".format(x.a))
As soon as you start to do proper object oriented design, and you have method functions that go along with the data, you want to have the data in a proper class so you can bundle the method functions in. It's legal to just have a dict and a handful of global functions that operate on it, but if they are all related, it just makes sense to bundle them up into a class
.
And finally, note that a dict
is a building-block that is used to implement a class
. If you store values in a class, they are actually stored inside an internal dict
and there is just some convenient syntax to access them.
print(x.a) # prints 1
print(x.__dict__["a"]) # does exact same thing as previous line