TL;DR - it depends on what you mean by a "variable". dicts act like python namespaces but allow more types of variable names.
Python objects have no inherent name. They can be referenced by one or more other objects and when their reference count goes to zero, they are deleted. When you assign an object to a variable, some data structure adds a reference to the the object and associates that object with the name. That data structure is the variable's namespace (that is, the context where the variable name is valid). And for most objects, that data structure is a dict
.
Lets look at two examples:
class Students:
pass
student_obj = Students()
and
student_dct = {}
I could treat Jake as a a variable
>>> student_obj.Jake = 12
>>> student_obj.Jake
12
>>> student_obj.__dict__
{'Jake': 12}
Or add it to the dict
>>> student_dct["Jake"] = 12
>>> student_dct["Jake"]
12
>>> student_dct
{'Jake': 12}
That's really close to the first example! The advantage to a variable is that it is parsed by python and python does the lookup for you. Python turns student_obj.Jake
into student_obj.__getattribute__("Jake")
. For normal class objects, python will check the object __dict__
for the name then fall back to containing namespaces. Classes that use __slots__
or are implemented in C follow different rules.
But variable assignment is a disadvantage if you want to use names that don't fit python's sytax rules.
>>> student_obj.Jim Bob = 12
File "<stdin>", line 1
student_obj.Jim Bob = 12
^
SyntaxError: invalid syntax
Here, you want "Jim Bob" to be a variable but it can't be used directly as a variable because it breaks python. So, you put it into a dict
>>> student_dct["Jim Bob"] = 12
So, dictionary items are "variables" (the value can be referenced and reassigned) but are not "python variables" because python doesn't implement the lookup for you.