source

두 Python 사전에 포함된 키의 차이 계산

manysource 2023. 6. 24. 09:19

두 Python 사전에 포함된 키의 차이 계산

두 개의 파이썬 사전을 가지고 있다고 가정해 보겠습니다.dictA그리고.dictB에있키있확합니다야인해에 있는 .dictB하지만 이 아닌dictA그것을 진행하는 가장 빠른 방법이 무엇입니까?

제가 사전 키를 세트로 변환한 다음에 돌아다녀야 합니까?

당신의 생각을 아는 것에 관심이 있습니다...


당신의 답변에 감사합니다.

제 질문을 제대로 말하지 못해서 죄송합니다.이렇습니다 - 는 시오이다니렇습있다습 - 저는니는리나제.dictA은 와같수있것는을과 수 .dictB또는 에 비해 일부 키가 누락되었을 수 있습니다.dictB그렇지 않으면 일부 키의 값이 다를 수 있습니다. 이 값은 다음 값으로 설정해야 합니다.dictA키 값

문제는 사전에 표준이 없고 받아쓰기가 가능한 값이 있을 수 있다는 것입니다.

말합니다

dictA={'key1':a, 'key2':b, 'key3':{'key11':cc, 'key12':dd}, 'key4':{'key111':{....}}}
dictB={'key1':a, 'key2:':newb, 'key3':{'key11':cc, 'key12':newdd, 'key13':ee}.......

따라서 'key2' 값을 새 값으로 재설정하고 'key13'을 딕트 안에 추가해야 합니다.키 값의 형식이 고정되어 있지 않습니다.단순 값이거나 딕트 또는 딕트일 수 있습니다.

키에 대해 설정 작업을 사용할 수 있습니다.

diff = set(dictb.keys()) - set(dicta.keys())

추가된 항목, 제거된 항목, 동일한 키-값 쌍, 변경된 키-값 쌍 등 모든 가능성을 찾을 수 있는 클래스가 있습니다.

class DictDiffer(object):
    """
    Calculate the difference between two dictionaries as:
    (1) items added
    (2) items removed
    (3) keys same in both but changed values
    (4) keys same in both and unchanged values
    """
    def __init__(self, current_dict, past_dict):
        self.current_dict, self.past_dict = current_dict, past_dict
        self.set_current, self.set_past = set(current_dict.keys()), set(past_dict.keys())
        self.intersect = self.set_current.intersection(self.set_past)
    def added(self):
        return self.set_current - self.intersect 
    def removed(self):
        return self.set_past - self.intersect 
    def changed(self):
        return set(o for o in self.intersect if self.past_dict[o] != self.current_dict[o])
    def unchanged(self):
        return set(o for o in self.intersect if self.past_dict[o] == self.current_dict[o])

다음은 몇 가지 샘플 출력입니다.

>>> a = {'a': 1, 'b': 1, 'c': 0}
>>> b = {'a': 1, 'b': 2, 'd': 0}
>>> d = DictDiffer(b, a)
>>> print "Added:", d.added()
Added: set(['d'])
>>> print "Removed:", d.removed()
Removed: set(['c'])
>>> print "Changed:", d.changed()
Changed: set(['b'])
>>> print "Unchanged:", d.unchanged()
Unchanged: set(['a'])

github repo: https://github.com/hughdbrown/dictdiffer

당신이 재귀적으로 차이를 원할 경우를 대비하여, 저는 파이썬을 위한 패키지를 작성했습니다: https://github.com/seperman/deepdiff

설치

PyPi에서 설치:

pip install deepdiff

사용 예

가져오는 중

>>> from deepdiff import DeepDiff
>>> from pprint import pprint
>>> from __future__ import print_function # In case running on Python 2

동일한 개체가 비어 있음을 반환합니다.

>>> t1 = {1:1, 2:2, 3:3}
>>> t2 = t1
>>> print(DeepDiff(t1, t2))
{}

항목 유형이 변경되었습니다.

>>> t1 = {1:1, 2:2, 3:3}
>>> t2 = {1:1, 2:"2", 3:3}
>>> pprint(DeepDiff(t1, t2), indent=2)
{ 'type_changes': { 'root[2]': { 'newtype': <class 'str'>,
                                 'newvalue': '2',
                                 'oldtype': <class 'int'>,
                                 'oldvalue': 2}}}

품목의 값이 변경되었습니다.

>>> t1 = {1:1, 2:2, 3:3}
>>> t2 = {1:1, 2:4, 3:3}
>>> pprint(DeepDiff(t1, t2), indent=2)
{'values_changed': {'root[2]': {'newvalue': 4, 'oldvalue': 2}}}

항목 추가 및/또는 제거

>>> t1 = {1:1, 2:2, 3:3, 4:4}
>>> t2 = {1:1, 2:4, 3:3, 5:5, 6:6}
>>> ddiff = DeepDiff(t1, t2)
>>> pprint (ddiff)
{'dic_item_added': ['root[5]', 'root[6]'],
 'dic_item_removed': ['root[4]'],
 'values_changed': {'root[2]': {'newvalue': 4, 'oldvalue': 2}}}

문자열 차이

>>> t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":"world"}}
>>> t2 = {1:1, 2:4, 3:3, 4:{"a":"hello", "b":"world!"}}
>>> ddiff = DeepDiff(t1, t2)
>>> pprint (ddiff, indent = 2)
{ 'values_changed': { 'root[2]': {'newvalue': 4, 'oldvalue': 2},
                      "root[4]['b']": { 'newvalue': 'world!',
                                        'oldvalue': 'world'}}}

문자열 차이 2

>>> t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":"world!\nGoodbye!\n1\n2\nEnd"}}
>>> t2 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":"world\n1\n2\nEnd"}}
>>> ddiff = DeepDiff(t1, t2)
>>> pprint (ddiff, indent = 2)
{ 'values_changed': { "root[4]['b']": { 'diff': '--- \n'
                                                '+++ \n'
                                                '@@ -1,5 +1,4 @@\n'
                                                '-world!\n'
                                                '-Goodbye!\n'
                                                '+world\n'
                                                ' 1\n'
                                                ' 2\n'
                                                ' End',
                                        'newvalue': 'world\n1\n2\nEnd',
                                        'oldvalue': 'world!\n'
                                                    'Goodbye!\n'
                                                    '1\n'
                                                    '2\n'
                                                    'End'}}}

>>> 
>>> print (ddiff['values_changed']["root[4]['b']"]["diff"])
--- 
+++ 
@@ -1,5 +1,4 @@
-world!
-Goodbye!
+world
 1
 2
 End

유형 변경

>>> t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2, 3]}}
>>> t2 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":"world\n\n\nEnd"}}
>>> ddiff = DeepDiff(t1, t2)
>>> pprint (ddiff, indent = 2)
{ 'type_changes': { "root[4]['b']": { 'newtype': <class 'str'>,
                                      'newvalue': 'world\n\n\nEnd',
                                      'oldtype': <class 'list'>,
                                      'oldvalue': [1, 2, 3]}}}

리스트차이

>>> t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2, 3, 4]}}
>>> t2 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2]}}
>>> ddiff = DeepDiff(t1, t2)
>>> pprint (ddiff, indent = 2)
{'iterable_item_removed': {"root[4]['b'][2]": 3, "root[4]['b'][3]": 4}}

목록 차이 2:

>>> t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2, 3]}}
>>> t2 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 3, 2, 3]}}
>>> ddiff = DeepDiff(t1, t2)
>>> pprint (ddiff, indent = 2)
{ 'iterable_item_added': {"root[4]['b'][3]": 3},
  'values_changed': { "root[4]['b'][1]": {'newvalue': 3, 'oldvalue': 2},
                      "root[4]['b'][2]": {'newvalue': 2, 'oldvalue': 3}}}

순서 또는 중복을 무시한 차이 나열: (위와 동일한 사전 포함)

>>> t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2, 3]}}
>>> t2 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 3, 2, 3]}}
>>> ddiff = DeepDiff(t1, t2, ignore_order=True)
>>> print (ddiff)
{}

사전이 포함된 목록:

>>> t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2, {1:1, 2:2}]}}
>>> t2 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2, {1:3}]}}
>>> ddiff = DeepDiff(t1, t2)
>>> pprint (ddiff, indent = 2)
{ 'dic_item_removed': ["root[4]['b'][2][2]"],
  'values_changed': {"root[4]['b'][2][1]": {'newvalue': 3, 'oldvalue': 1}}}

세트:

>>> t1 = {1, 2, 8}
>>> t2 = {1, 2, 3, 5}
>>> ddiff = DeepDiff(t1, t2)
>>> pprint (DeepDiff(t1, t2))
{'set_item_added': ['root[3]', 'root[5]'], 'set_item_removed': ['root[8]']}

명명된 튜플:

>>> from collections import namedtuple
>>> Point = namedtuple('Point', ['x', 'y'])
>>> t1 = Point(x=11, y=22)
>>> t2 = Point(x=11, y=23)
>>> pprint (DeepDiff(t1, t2))
{'values_changed': {'root.y': {'newvalue': 23, 'oldvalue': 22}}}

사용자 지정 개체:

>>> class ClassA(object):
...     a = 1
...     def __init__(self, b):
...         self.b = b
... 
>>> t1 = ClassA(1)
>>> t2 = ClassA(2)
>>> 
>>> pprint(DeepDiff(t1, t2))
{'values_changed': {'root.b': {'newvalue': 2, 'oldvalue': 1}}}

개체 특성이 추가되었습니다.

>>> t2.c = "new attribute"
>>> pprint(DeepDiff(t1, t2))
{'attribute_added': ['root.c'],
 'values_changed': {'root.b': {'newvalue': 2, 'oldvalue': 1}}}

그것이 "빠른"지 아닌지 확실하지 않지만, 보통, 사람은 이것을 할 수 있습니다.

dicta = {"a":1,"b":2,"c":3,"d":4}
dictb = {"a":1,"d":2}
for key in dicta.keys():
    if not key in dictb:
        print key

, 키가 A에 , Alex Martelli 썼듯이, 만약에당 B있에어는떤키가신, A지있않확은고싶하인면다지,any(True for k in dictB if k not in dictA)그게 최선의 방법일 겁니다.

누락된 키 찾기

diff = set(dictB)-set(dictA) #sets

C:\Dokumente und Einstellungen\thc>python -m timeit -s "dictA =    
dict(zip(range(1000),range
(1000))); dictB = dict(zip(range(0,2000,2),range(1000)))" "diff=set(dictB)-set(dictA)"
10000 loops, best of 3: 107 usec per loop

diff = [ k for k in dictB if k not in dictA ] #lc

C:\Dokumente und Einstellungen\thc>python -m timeit -s "dictA = 
dict(zip(range(1000),range
(1000))); dictB = dict(zip(range(0,2000,2),range(1000)))" "diff=[ k for k in dictB if
k not in dictA ]"
10000 loops, best of 3: 95.9 usec per loop

그래서 이 두 가지 해결책은 거의 같은 속도입니다.

만약 당신이 정말로 말하는 것을 정확히 의미한다면(만약 있다면 어떤 것이 될 수 있는지가 아니라 B에 "열쇠가 있는지"만 알면 된다는 것), 가장 빠른 방법은 다음과 같습니다.

if any(True for k in dictB if k not in dictA): ...

만약 당신이 그러한 키가 단순히 "만약"이 아니라, 만약 있다면, 어떤 키가 A에 있지 않고, B에 있는지 실제로 알아내야 한다면, 기존의 대답은 상당히 적절합니다. (하지만 만약 당신이 정말로 의미한다면, 나는 미래의 질문에 더 정확한 것을 제안합니다;-).

Hughbrown의 최고 답변은 설정 차이를 사용하는 것을 제안하며, 이는 확실히 최고의 접근 방식입니다.

diff = set(dictb.keys()) - set(dicta.keys())

이 코드의 문제는 단지 두 세트를 만들기 위해 두 개의 목록을 작성하기 때문에 4N의 시간과 2N의 공간을 낭비한다는 것입니다.필요 이상으로 복잡하기도 합니다.

일반적으로, 이것은 큰 문제가 아니지만, 만약 그렇다면:

diff = dictb.keys() - dicta
  • 올바른 dict를 집합으로 변환할 필요는 없습니다. 설정 차이는 반복 가능하며 dict는 해당 키의 반복 가능합니다.
  • 또한 왼쪽 딕트를 집합으로 변환할 필요가 없습니다. 호환되는 모든 항목에는 와 같은 역할을 하기 때문입니다.

파이썬 2

에서 파썬에 2서이는keys()합니다. 키 목록이 아닌 키 을 반환합니다.KeysView그래서 당신은 요청해야 합니다.viewkeys()직접적으로.

diff = dictb.viewkeys() - dicta

2코드의 경우 듀얼버 2.7/3.x 경다사수있다습니를 사용하고 입니다.six또는 유사한 것을 사용할 수 있습니다.

diff = six.viewkeys(dictb) - dicta

2.4-2.6에서는 다음이 없습니다.KeysView그러나 목록을 먼저 작성하는 대신 반복기에서 직접 왼쪽 세트를 구축하여 적어도 4N에서 N으로 비용을 절감할 수 있습니다.

diff = set(dictb) - dicta

항목들

dictB와 동일하거나 dictB와 비교하여 일부 키가 누락되었거나 일부 키의 값이 다를 수 있는 dictA가 있습니다.

따라서 키를 비교할 필요가 없고 항목만 비교할 필요가 있습니다.안 안ItemsView에 지나지 않습니다.Set값이 해시 가능한 경우(예: 문자열).그렇다면 간단합니다.

diff = dictb.items() - dicta.items()

재귀 diff

질문이 재귀적 디프를 직접 묻는 것은 아니지만 일부 예제 값은 딕트이며 예상 출력이 재귀적 디프를 수행하는 것으로 보입니다.이 방법을 보여주는 여러 개의 답변이 이미 있습니다.

사용:

set(dictA.keys()).intersection(dictB.keys())

인수에 대한 스택 오버플로에 대한 또 다른 질문이 있으며 설명된 간단한 해결책이 있다는 것을 인정해야 합니다. 파이썬의 datadiff 라이브러리는 두 사전 간의 차이를 인쇄하는 데 도움이 됩니다.

하여 같방평수있다습니가할로으법다음과은▁to▁that다▁here▁evaluate,▁for▁allows니있습▁keys▁way'False가능하면 일찍 빠지기 위해 여전히 생성기 표현을 사용합니다.특별히 예쁜 것은 아닙니다.

any(map(lambda x: True, (k for k in b if k not in a)))

편집:

THC4k는 다른 답변에 제 의견에 대한 답변을 올렸습니다.위와 같은 작업을 수행하는 더 나은 방법이 있습니다.

any(True for k in b if k not in a)

어떻게 그런 생각이 안 들었는지 모르겠어요

이것은 오래된 질문이고 제가 필요로 하는 것보다 조금 적게 질문하기 때문에 이 대답은 실제로 이 질문보다 더 많이 해결됩니다.이 질문의 답변은 다음을 해결하는 데 도움이 되었습니다.

  1. (요청됨) 두 사전 간의 차이 기록
  2. #1의 차이점을 기본 사전에 병합
  3. (요청됨) 두 사전 간의 차이 병합(사전 #2를 디프 사전처럼 처리)
  4. 항목 이동 및 변경 사항 탐지
  5. (요청됨) 이 모든 것을 반복적으로 수행합니다.

이 모든 것이 JSON과 결합되어 매우 강력한 구성 스토리지 지원을 제공합니다.

솔루션(github에서도 사용):

from collections import OrderedDict
from pprint import pprint


class izipDestinationMatching(object):
    __slots__ = ("attr", "value", "index")

    def __init__(self, attr, value, index):
        self.attr, self.value, self.index = attr, value, index

    def __repr__(self):
        return "izip_destination_matching: found match by '%s' = '%s' @ %d" % (self.attr, self.value, self.index)


def izip_destination(a, b, attrs, addMarker=True):
    """
    Returns zipped lists, but final size is equal to b with (if shorter) a padded with nulls
    Additionally also tries to find item reallocations by searching child dicts (if they are dicts) for attribute, listed in attrs)
    When addMarker == False (patching), final size will be the longer of a, b
    """
    for idx, item in enumerate(b):
        try:
            attr = next((x for x in attrs if x in item), None)  # See if the item has any of the ID attributes
            match, matchIdx = next(((orgItm, idx) for idx, orgItm in enumerate(a) if attr in orgItm and orgItm[attr] == item[attr]), (None, None)) if attr else (None, None)
            if match and matchIdx != idx and addMarker: item[izipDestinationMatching] = izipDestinationMatching(attr, item[attr], matchIdx)
        except:
            match = None
        yield (match if match else a[idx] if len(a) > idx else None), item
    if not addMarker and len(a) > len(b):
        for item in a[len(b) - len(a):]:
            yield item, item


def dictdiff(a, b, searchAttrs=[]):
    """
    returns a dictionary which represents difference from a to b
    the return dict is as short as possible:
      equal items are removed
      added / changed items are listed
      removed items are listed with value=None
    Also processes list values where the resulting list size will match that of b.
    It can also search said list items (that are dicts) for identity values to detect changed positions.
      In case such identity value is found, it is kept so that it can be re-found during the merge phase
    @param a: original dict
    @param b: new dict
    @param searchAttrs: list of strings (keys to search for in sub-dicts)
    @return: dict / list / whatever input is
    """
    if not (isinstance(a, dict) and isinstance(b, dict)):
        if isinstance(a, list) and isinstance(b, list):
            return [dictdiff(v1, v2, searchAttrs) for v1, v2 in izip_destination(a, b, searchAttrs)]
        return b
    res = OrderedDict()
    if izipDestinationMatching in b:
        keepKey = b[izipDestinationMatching].attr
        del b[izipDestinationMatching]
    else:
        keepKey = izipDestinationMatching
    for key in sorted(set(a.keys() + b.keys())):
        v1 = a.get(key, None)
        v2 = b.get(key, None)
        if keepKey == key or v1 != v2: res[key] = dictdiff(v1, v2, searchAttrs)
    if len(res) <= 1: res = dict(res)  # This is only here for pretty print (OrderedDict doesn't pprint nicely)
    return res


def dictmerge(a, b, searchAttrs=[]):
    """
    Returns a dictionary which merges differences recorded in b to base dictionary a
    Also processes list values where the resulting list size will match that of a
    It can also search said list items (that are dicts) for identity values to detect changed positions
    @param a: original dict
    @param b: diff dict to patch into a
    @param searchAttrs: list of strings (keys to search for in sub-dicts)
    @return: dict / list / whatever input is
    """
    if not (isinstance(a, dict) and isinstance(b, dict)):
        if isinstance(a, list) and isinstance(b, list):
            return [dictmerge(v1, v2, searchAttrs) for v1, v2 in izip_destination(a, b, searchAttrs, False)]
        return b
    res = OrderedDict()
    for key in sorted(set(a.keys() + b.keys())):
        v1 = a.get(key, None)
        v2 = b.get(key, None)
        #print "processing", key, v1, v2, key not in b, dictmerge(v1, v2)
        if v2 is not None: res[key] = dictmerge(v1, v2, searchAttrs)
        elif key not in b: res[key] = v1
    if len(res) <= 1: res = dict(res)  # This is only here for pretty print (OrderedDict doesn't pprint nicely)
    return res

스탠드 아트는 어떻습니까(전체 개체 비교).

PyDev->새로운 PyDev 모듈->모듈: 유닛 테스트

import unittest


class Test(unittest.TestCase):


    def testName(self):
        obj1 = {1:1, 2:2}
        obj2 = {1:1, 2:2}
        self.maxDiff = None # sometimes is usefull
        self.assertDictEqual(d1, d2)

if __name__ == "__main__":
    #import sys;sys.argv = ['', 'Test.testName']

    unittest.main()

Python » 2.7의 경우:

# update different values in dictB
# I would assume only dictA should be updated,
# but the question specifies otherwise

for k in dictA.viewkeys() & dictB.viewkeys():
    if dictA[k] != dictB[k]:
        dictB[k]= dictA[k]

# add missing keys to dictA

dictA.update( (k,dictB[k]) for k in dictB.viewkeys() - dictA.viewkeys() )

다음은 두 개의 사전 키를 심층 비교하는 솔루션입니다.

def compareDictKeys(dict1, dict2):
  if type(dict1) != dict or type(dict2) != dict:
      return False

  keys1, keys2 = dict1.keys(), dict2.keys()
  diff = set(keys1) - set(keys2) or set(keys2) - set(keys1)

  if not diff:
      for key in keys1:
          if (type(dict1[key]) == dict or type(dict2[key]) == dict) and not compareDictKeys(dict1[key], dict2[key]):
              diff = True
              break

  return not diff

다음은 두 개 이상의 딕트를 비교할 수 있는 솔루션입니다.

def diff_dict(dicts, default=None):
    diff_dict = {}
    # add 'list()' around 'd.keys()' for python 3 compatibility
    for k in set(sum([d.keys() for d in dicts], [])):
        # we can just use "values = [d.get(k, default) ..." below if 
        # we don't care that d1[k]=default and d2[k]=missing will
        # be treated as equal
        if any(k not in d for d in dicts):
            diff_dict[k] = [d.get(k, default) for d in dicts]
        else:
            values = [d[k] for d in dicts]
            if any(v != values[0] for v in values):
                diff_dict[k] = values
    return diff_dict

사용 예:

import matplotlib.pyplot as plt
diff_dict([plt.rcParams, plt.rcParamsDefault, plt.matplotlib.rcParamsOrig])

두 사전 사이의 대칭적인 차이에 대한 나의 요리법:

def find_dict_diffs(dict1, dict2):
    unequal_keys = []
    unequal_keys.extend(set(dict1.keys()).symmetric_difference(set(dict2.keys())))
    for k in dict1.keys():
        if dict1.get(k, 'N\A') != dict2.get(k, 'N\A'):
            unequal_keys.append(k)
    if unequal_keys:
        print 'param', 'dict1\t', 'dict2'
        for k in set(unequal_keys):
            print str(k)+'\t'+dict1.get(k, 'N\A')+'\t '+dict2.get(k, 'N\A')
    else:
        print 'Dicts are equal'

dict1 = {1:'a', 2:'b', 3:'c', 4:'d', 5:'e'}
dict2 = {1:'b', 2:'a', 3:'c', 4:'d', 6:'f'}

find_dict_diffs(dict1, dict2)

결과는 다음과 같습니다.

param   dict1   dict2
1       a       b
2       b       a
5       e       N\A
6       N\A     f

다른 답변에서 언급했듯이, 단위 테스트는 딕트를 비교하기 위한 몇 가지 좋은 출력을 생성하지만, 이 예에서는 먼저 전체 테스트를 작성할 필요가 없습니다.

유닛 테스트 소스를 스크랩하면 다음과 같은 방법으로 공정한 솔루션을 얻을 수 있습니다.

import difflib
import pprint

def diff_dicts(a, b):
    if a == b:
        return ''
    return '\n'.join(
        difflib.ndiff(pprint.pformat(a, width=30).splitlines(),
                      pprint.pformat(b, width=30).splitlines())
    )

그렇게

dictA = dict(zip(range(7), map(ord, 'python')))
dictB = {0: 112, 1: 'spam', 2: [1,2,3], 3: 104, 4: 111}
print diff_dicts(dictA, dictB)

결과:

{0: 112,
-  1: 121,
-  2: 116,
+  1: 'spam',
+  2: [1, 2, 3],
   3: 104,
-  4: 111,
?        ^

+  4: 111}
?        ^

-  5: 110}

위치:

  • 두 번째 딕트가 아닌 첫 번째 딕트의 키/값을 나타냅니다.
  • 첫 번째 딕트가 아닌 두 번째 키/값을 나타냅니다.

유닛 테스트와 마찬가지로 마지막 매핑이 뒤에 오는 쉼표/괄호 때문에 디프로 간주될 수 있다는 것이 유일한 경고입니다.

두 사전 모두에 있는 키인 교차점을 찾으려면 이 방법을 사용하십시오. 두 번째 사전에서 키를 찾지 않으려면 다음 항목을 사용하십시오.

intersect = filter(lambda x, dictB=dictB.keys(): x in dictB, dictA.keys())

@Maxx 훌는가있습다니지고변을답륭을 하세요.unittestPython에서 제공하는 도구:

import unittest


class Test(unittest.TestCase):
    def runTest(self):
        pass

    def testDict(self, d1, d2, maxDiff=None):
        self.maxDiff = maxDiff
        self.assertDictEqual(d1, d2)

코드 내 어디서나 전화할 수 있습니다.

try:
    Test().testDict(dict1, dict2)
except Exception, e:
    print e

은 " ▁output다"의 출력과 같습니다.diff로 사전을 예쁘게 인쇄하기+또는-서로 다른 각 행 앞에 추가합니다.

아직 관련성이 있는지 확실하지 않지만 이 문제를 발견했습니다. 제 상황은 모든 중첩된 사전 등에 대한 변경 사항 사전을 반환하기만 하면 되었습니다.좋은 해결책을 찾지 못했지만 결국 이를 위한 간단한 기능을 작성하게 되었습니다.이게 도움이 되길 바랍니다.

임의의 딕트 구조와 완전하게 비교할 수 있는 내장 솔루션을 원한다면, @Maxx의 대답은 좋은 시작입니다.

import unittest

test = unittest.TestCase()
test.assertEqual(dictA, dictB)

고스트독74의 답변을 토대로,

dicta = {"a":1,"d":2}
dictb = {"a":5,"d":2}

for value in dicta.values():
    if not value in dictb.values():
        print value

다른 값의 딕타를 인쇄합니다.

언급URL : https://stackoverflow.com/questions/1165352/calculate-difference-in-keys-contained-in-two-python-dictionaries