8

如何比较两个 OrderedDict 字典?

我的结构如下:

dict_a = OrderedDict([(1,4), (2,5), (3,3), (4,5), (5,4), (6,4), (7,4), (8,3), (9,4)])

dict_b = OrderedDict([(1,4), (2,2), (3,1), (4,4), (5,6), (6,7), (7,4), (8,2), (9,5)])

for values in score_dict.items():
if values == course_dict.values():
    print 'match!'
else:
    print 'No match!'

它遍历并且两个列表都是有序的,所以它应该在 1 和 7 上匹配?提前致谢!

4

6 回答 6

14

您可以使用items()和内置zip()功能:

for i, j in zip(dict_a.items(), dict_b.items()):
    if i == j:
        print(i)

输出:

(1, 4)
(7, 4)
于 2012-08-14T21:43:14.413 回答
4

如果您希望每个有序位置的相交元素相同:

>>> from collections import OrderedDict
>>> dict_a = OrderedDict([(1,4), (2,5), (3,3), (4,5), (5,4), (6,4), (7,4), (8,3), (9,4)])
>>> dict_b = OrderedDict([(1,4), (2,2), (3,1), (4,4), (5,6), (6,7), (7,4), (8,2), (9,5)])
>>> [i1 for i1, i2 in zip(dict_a.iteritems(), dict_b.iteritems()) if i1 == i2]
[(1, 4), (7, 4)]

如果您不关心订购:

>>> set(dict_a.items()).intersection(set(dict_b.items()))
set([(7, 4), (1, 4)])
于 2012-08-14T21:38:15.267 回答
1
>>> for x in dict_a.items():
    if x in dict_b.items():
        print(x)


(1, 4)
(7, 4)
于 2012-08-14T21:38:37.750 回答
1

如果您发现它们相等,您可以遍历这些项目并打印它。

In [10]: for a, b in zip(dict_a.items(), dict_b.items()):
   ....:     if a == b:
   ....:         print True
   ....:     else:
   ....:         print False
于 2012-08-14T21:51:55.517 回答
0

如果您想在 OrderedDict 中包含索引作为比较的一部分:

>>> [a[0] for a, b in zip(dict_a.items(), dict_b.items()) if a == b]
[1, 7]

如果要获取两个 OrderedDicts 中具有相同值的所有键,无论顺序如何:

>>> [k for k, v in dict_a.items() if k in dict_b and dict_b[k] == v]
[1, 7]
于 2012-08-14T21:44:49.523 回答
0

假设您希望键和值都匹配,但不关心每个中的位置OrderedDict

for k, v in dict_a.items():
  if v == dict_b[k]:
    print '(%s, %s)' % (k, v)
于 2012-08-14T21:43:15.767 回答