字典的差异

时间:2011-07-09 02:05:09

标签: python dictionary

我正在试图弄清楚dict中的区别,无论是添加还是删除某些内容以及是什么。

以下是添加值的情况:

original = {0: None, 1: False, 2: [16]}
new = {0: None, 1: False, 2: [2, 16]}

difference = True, {2: 2} # True = Added

以下是删除值的情况:

original = {0: None, 1: False, 2: [16, 64]}
new = {0: None, 1: False, 2: [64]}

difference = False, {2: 16} # False = Removed

问题在于我不知道如何收集差异。有人会碰巧知道如何实现这样的结果吗?

额外信息(不知道你是否需要这个):

  • 这也适用于0和1的原版和新版。
  • 1和2不能同时激活。如果有值,则另一个为假。

6 个答案:

答案 0 :(得分:6)

正如我在other question中所解释的那样,PyPI上只有一个用于此任务的库,datadiff library。它易于使用,您可以使用输出来完成您必须做的事情。

答案 1 :(得分:3)

我觉得这很可读:

def dict_diff(left, right):
    diff = dict()
    diff['left_only'] = set(left) - set(right)
    diff['right_only'] = set(right) - set(left)
    diff['different'] = {k for k in set(left) & set(right) if left[k]!=right[k]}
    return diff

>>> d1 = dict(a=1, b=20, c=30, e=50)
>>> d2 = dict(a=1, b=200, d=400, e=500)
>>> dict_diff(d1, d2)
{'different': {'b', 'e'}, 'left_only': {'c'}, 'right_only': {'d'}}

答案 2 :(得分:2)

这是一个函数的链接,可以产生两个字典的“差异”,然后是附加的注释/代码示例:

http://code.activestate.com/recipes/576644-diff-two-dictionaries/

包括以下代码:

KEYNOTFOUND = '<KEYNOTFOUND>'       # KeyNotFound for dictDiff

def dict_diff(first, second):
    """ Return a dict of keys that differ with another config object.  If a value is
        not found in one fo the configs, it will be represented by KEYNOTFOUND.
        @param first:   Fist dictionary to diff.
        @param second:  Second dicationary to diff.
        @return diff:   Dict of Key => (first.val, second.val)
    """
    diff = {}
    # Check all keys in first dict
    for key in first.keys():
        if (not second.has_key(key)):
            diff[key] = (first[key], KEYNOTFOUND)
        elif (first[key] != second[key]):
            diff[key] = (first[key], second[key])
    # Check all keys in second dict to find missing
    for key in second.keys():
        if (not first.has_key(key)):
            diff[key] = (KEYNOTFOUND, second[key])
    return diff

答案 3 :(得分:1)

您可以暂时将dic [2]转移到python中的set,并使用-来获得差异

答案 4 :(得分:0)

如下:

def diff(a,b):
     ret_dict = {}
     for key,val in a.items():
         if b.has_key(key):
             if b[key] != val:
                 ret_dict[key] = [val,b[key]]
         else:
             ret_dict[key] = [val]
     for key,val in b.items():
         ret_dict.setdefault(key,[val])
     return ret_dict

答案 5 :(得分:-1)

这可以在一行中完成。

for i = n..1:
    if F[i - 1][k - a[i]] == True then
         output a[i] to the answer
         k -= a[i]
         if k == 0
             break