比较字典python字典中的值

时间:2014-03-13 16:34:14

标签: python dictionary nested

我有这个嵌套字典,我想检查一下这些值是否匹配以及它们是否不返回值。

dict_test = {'sct2': {(5, 5, 0): [1, 2, 3]}, 'sct1': {(5, 5, 0): [1, 2, 4]}}

所以基本上从迭代到dict_test我会比较来自' sct2'和' sct1'字典并查看它们是否匹配,如果它们不会打印出不匹配的值。如果我分成2个词典而不是比较它们,我可以这样做

test1=dict_test['sct2']
test2=dict_test['sct1']

并且我可以比较2个词典并做这样的事情:

mismatch = [val for val in test1.itervalues() if not val in test2.itervalues()]

将返回[1,2,4]虽然我希望它返回4而不是列表

我想知道是否有更好的方法来做到这一点,而不必创建2个词典,任何帮助表示赞赏。感谢

3 个答案:

答案 0 :(得分:0)

使用minus operator of sets,它给出了两组的差异。为了清楚起见,您可以使用差异方法,这也可以给出差异。

mismatch = list(filter(set(s2)-set(s1) for s1 in dict_test["sct2"].values()\
            for s2 in dict_test["sct1"].values()))

答案 1 :(得分:0)

如果您没有更好地了解您尝试解决的问题,那么此处的代码将根据您的((3,4))返回test_dict。如果您想要更好地解决问题的答案,请更清楚地说明您的问题,限制和要求。

def diffList(a,b):
    '''Assumption: a and b are same length
    Returns non-matching ordered pairs of a and b
    '''
    return filter(lambda ai, bi: ai != bi, zip(a,b)))

outerKeyPairs = [(outerKeyA, outerKeyB) for outerKeyA in test_dict for outerKeyB in test_dict if outerKeyA > outerKeyB]
for outerKeyA, outerKeyB in outerKeyPairs:
    for innerKey in test_dict[outerKeyA]:
        if innerKey in test_dict[outerKeyB]:
            yield diffList(test_dict[outerKeyA][innerKey], test_dict[outerKeyB][innerKey])

答案 2 :(得分:0)

一个相当干净的方法是:

def diff_list(l1, l2):
    s = set(l2)
    return [i for i in l1 if i not in s]

{t:diff_list(l1, test2[t]) for (t,l1) in test1.iteritems()}

这会生成每个不同键的映射,其中包含缺少值的列表:

{(5, 5, 0): [3]}

请注意,上面diff_list的逻辑假定您并不关心每个列表中项目的位置和数量。如果这很重要,diff_list可以实现为:

def diff_list(l1, l2):
    return {i: (v[0], v[1]) for i,v in enumerate(map(None, l1, l2)) if v[0] != v[1]}

使用此方法,您将获得以下输出:

>>> test1  # Here's what test1 looks like
{(5, 5, 0): [1, 2, 3]}

>>> test2  # Here's what test2 looks like
{(5, 5, 0): [1, 2, 4]}

>>> {t:diff_list(l1, test2[t]) for (t,l1) in test1.iteritems()} # Getting the difference
{(5, 5, 0): {2: (3, 4)}}

也就是说,你得到一个包含test1test2中每个不同键的字典,映射到包含不同索引的字典,以及两个索引中的值。不同的清单。