通过对象字符串表示而不是对象访问字典中的键

时间:2017-09-21 11:45:34

标签: python dictionary

我有一个python字典,它由特定类的对象元组键入:

class MyClass:

    def __init__(self, label):
        self.label = label

    def __str__(self):
        return self.label

    def __repr__(self):
        return self.label

obj1 = MyClass('obj1')
obj2 = MyClass('obj2')
obj3 = MyClass('obj3')
obj4 = MyClass('obj4')

my_dict = {(obj1, obj2): 'foo', (obj3, obj4): 'bar'}

print(my_dict[(obj1, obj2)])

# this should also be possible (string API for dict): 
# print(my_dict[('obj1', 'obj2')])
# which works with the following code but seems to be not the best solution
my_dict2 = {tuple([str(e) for e in k]): v for k, v in my_dict.items()}
print(my_dict2[('obj1', 'obj2')])

现在我想通过使用具有对象字符串表示的键来提供访问元素的可能性,例如my_dict[('obj1', 'obj2')我不确定如何以干净有效的方式解决这个问题。

我的第一个也许是显而易见的想法是将所有密钥转换为字符串,例如('obj1','obj2')在另一个字典中。

但是,是否有一种更优雅的方式在同一个dict上提供两种访问选项(keys = objects / strings),比如重写字典类并提供其他方法或编写一些排序包装函数?什么是解决这个问题的好方法?

非常感谢任何帮助。提前谢谢!

0 个答案:

没有答案
相关问题