How To Change Class Representation When The Class Is A Dictionary's Key?
Consider the following code: class DummyClass: def __init__(self, name): self.name = name obj_1 = DummyClass('name_1') obj_2 = DummyClass('name_2') my_dict = {
Solution 1:
The __repr__
method is used to generate the string that dict
uses to display the keys. There is no mechanism to modify the key during dict
creation or update, and no dict
-specific way to modify how the key is displayed.
By default, DummyClass
is inheriting its __repr__
method from object
, which is what produces the <...>
string. Override __repr__
to return a string built from the name
attribute.
classDummyClass:def__init__(self, name):
self.name = name
def__repr__(self):
return f"'{self.name}'"
There was a proposal to create a key-transforming dictionary, but it was rejected. It would have allowed you to write something like
d = TransformDict(lambda x: x.name)
d[obj_1] = ...
d[obj_2] = ...
and the resulting dict
would behave as if 'name1'
and 'name2'
were the keys (while still allowing access to the original keys obj_1
and obj_2
if necessary).
Post a Comment for "How To Change Class Representation When The Class Is A Dictionary's Key?"