Testing for Equality and Adding Attributes
Testing for Equality and Adding New Attributes to Ordered Dictionaries. When you test two
OrderedDict objects for equality in a Boolean context, the order of items plays an important role. For example, if your ordered dictionaries contain the same set of items, then the result of the test depends on their order.
letters_1 has a slight difference in the order of its items compared to
letters_2, so this test returns
letters_2 have the same set of items in the same order, so this test returns
True. If you try this same example using regular dictionaries, then the results are different.
When you test two regular dictionaries for equality, you get
True if both dictionaries have the same set of items, regardless of their order.
Finally, equality tests between an
OrderedDict and a regular dictionary don’t take the order of items into account.
If both dictionaries have the same set of items, then they compare equally, regardless of the order.
OrderedDict objects have a
.__dict__ attribute that you can’t find in regular dictionary objects.
First, you access the
.__dict__ attribute on the ordered dictionary
letters. Python internally uses this attribute to store writable instance attributes.
And this shows that regular dictionary objects don’t have a
.__dict__ attribute. If you try to access the
.__dict__ attribute on a regular dictionary, you get an
You can use the order dictionary’s
.__dict__ attribute to store dynamically created writable instance attributes. There are several ways to do this.
You can use the dictionary-style assignment, or you can use dot notation. Here’s an example of using
.__dict__ to attach a new function to an existing ordered dictionary.
Now you have a
lambda function attached to your
letters order dictionary. Note that you can inspect the content of
.__dict__ either by accessing it directly with dot notation or by using
This kind of dynamic attribute is added to a particular instance of a given class. In the example seen on-screen, that instance is
This affects neither other instances nor the class itself, so you only have access to
letters. You can use this dynamically added function to iterate through the dictionary keys in sorted order without altering the original order of
This is just an example of how useful this feature of
OrderedDict can be. Note that you can’t do something similar with a regular dictionary.
If you try to dynamically add custom instance attributes to a regular dictionary, then you get an
AttributeError telling you that the underlying dictionary doesn’t have the attribute at hand.
That’s because regular dictionaries don’t have a
.__dict__ attribute to hold new instance attributes. In the next section of the course, you’ll see how to merge and update dictionaries with operators.
Become a Member to join the conversation.