What does the == operator actually do on a Python dictionary?

后端 未结 3 1904
谎友^
谎友^ 2020-12-03 04:14

Consider:

>>> a = {\'foo\': {\'bar\': 3}}
>>> b = {\'foo\': {\'bar\': 3}}
>>> a == b
True

According to the pyth

3条回答
  •  悲&欢浪女
    2020-12-03 04:56

    From docs:

    Mappings (dictionaries) compare equal if and only if their sorted (key, value) lists compare equal .[5] Outcomes other than equality are resolved consistently, but are not otherwise defined. [6]

    Footnote [5]:

    The implementation computes this efficiently, without constructing lists or sorting.

    Footnote [6]:

    Earlier versions of Python used lexicographic comparison of the sorted (key, value) lists, but this was very expensive for the common case of comparing for equality. An even earlier version of Python compared dictionaries by identity only, but this caused surprises because people expected to be able to test a dictionary for emptiness by comparing it to {}.

提交回复
热议问题