首页 > 解决方案 > Python 字典比较 == 如何在幕后工作?

问题描述

我正在使用 == 比较两个字典,如果键和对应的值相似,则返回 true。即使重新排序字典结果也是如此。但我想知道它是如何在幕后发生的。我打印了字典项的 id,发现两个字典中具有相同键或值的所有字典项都具有相同的 id。那么 Python 会比较两个字典中的 id 吗?

dict1 = {'marks': 23}

for key, value in dict1.items():
    print(f'Key: {key} with id:{id(key)} :=: value:{value} with id:{id(value)}')

dict2 = {'marks': 23}

for key, value in dict2.items():
    print(f'Key: {key} with id:{id(key)} :=: value:{value} with id:{id(value)}')

dict1 == dict2

输出

Key: marks with id:4477545520 :=: value:23 with id:4456492064
Key: marks with id:4477545520 :=: value:23 with id:4456492064
True

这里还有一个问题是如果我打印元组的 id 那么为什么它在每次执行时打印不同的值?

for i in range (1, 11):
    for item in dict1.items():
        print(f'{i}: item: {item} with id:{id(item)}')

Output:

1: item: ('marks', 23) with id:4546950464
2: item: ('marks', 23) with id:4546764672
3: item: ('marks', 23) with id:4546873984
4: item: ('marks', 23) with id:4547194816
5: item: ('marks', 23) with id:4546711424
6: item: ('marks', 23) with id:4547191680
7: item: ('marks', 23) with id:4546735552
8: item: ('marks', 23) with id:4546929088
9: item: ('marks', 23) with id:4546773696
10: item: ('marks', 23) with id:4546776832

标签: python

解决方案


需要注意的重要一点是,如果两个变量指向同一个对象,“is”将返回 True。== 如果变量引用的对象相等,则返回 true。

这里参考python的实现:

https://github.com/python/cpython/blob/490c5426b1b23831d83d0c6b269858fb98450889/Objects/dictobject.c#L2844-L2892

默认情况下,如果两个字典具有相同的键和值,则它们是相等的。

理解它是如何工作的最好方法是在你自己的类中实现相等。例如:

class MyClass:
    def __init__(self, foo, bar):
        self.foo = foo
        self.bar = bar

    def __eq__(self, other): 
        if not isinstance(other, MyClass):
            # don't attempt to compare against unrelated types
            return NotImplemented

        return self.foo == other.foo and self.bar == other.bar

尝试实现您自己的类的相等性,或查看您感兴趣的其他数据类型如何实现相等性的源代码。

如果它解决了您的问题,请将此答案标记为正确。


推荐阅读