def smallest_diff_key(A, B): """return the smallest key adiff in A such that A[adiff] != B[bdiff]""" diff_keys = [k for k in A if A.get(k) != B.get(k)] return min(diff_keys) def dict_cmp(A, B): if len(A) != len(B): return cmp(len(A), len(B)) adiff = smallest_diff_key(A, B) bdiff = smallest_diff_key(B, A) if adiff != bdiff: return cmp(adiff, bdiff) return cmp(A[adiff], b[bdiff])
stackoverflow上有关dict的cmp的实现,代码如下:
先比较字典的长度,如果相等。再比较adiff(在A中与B值不相等的最小key)和bdiff(在B中与A值不相等的最小key),再等则比较两者的值。
长度相等,直接比较'Addr'和'Adds',所以dict1 < dict2
长度相等,key完全相等,比较value不等keys('Name','Age','Addr')中的最小key('Addr')的value('hust','whu'),所以dict1 < dict2
详情见stackoverflow