Ada*_*mar 3 python dictionary python-2.7
我遇到了这个:
>>> d1 = {"john":40, "peter":45}
>>> d2 = {"john":466, "peter":45}
>>> d1 > d2
False
Run Code Online (Sandbox Code Playgroud)
比较运算符在比较两个dicts时是做什么的False?它是如何输出的?
由于这些dicts长度相等,我们找到相应值不相等的最小键,即'john'.然后将该词与该键的值进行比较.
演示:
>>> d1 = {"john":40, "peter":45}
>>> d2 = {"john":466, "peter":45}
>>> d1 < d2
True
>>> d2['john'] = 39
>>> d1 < d2
False
Run Code Online (Sandbox Code Playgroud)
自从20多年前Guido的承诺以来,这个基本思想基本没有改变:
$ git show a0a69b8
commit a0a69b8b429f3d4c91f1c432247cfda017505976
Author: Guido van Rossum <guido@python.org>
Date: Thu Dec 5 21:55:55 1996 +0000
Experimental new implementation of dictionary comparison. This
defines that a shorter dictionary is always smaller than a longer one.
For dictionaries of the same size, the smallest differing element
determines the outcome (which yields the same results as before,
without explicit sorting).
Run Code Online (Sandbox Code Playgroud)
它没有记录,并且在Python 3中删除了dict比较代码,所以对于任何重要的事情我都不会依赖它.相关的CPython源码在这里.
有趣的事实:显然,在旧版本的Python中,某些字典比较可能会使运行时崩溃,甚至可能导致Windows 98重启.嘿.