티스토리 뷰

반응형

Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.

Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.

 

아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.

Comparing two dictionaries and checking how many (key, value) pairs are equal

두 개의 딕셔너리를 비교하고 (key, value) 쌍이 얼마나 일치하는지 확인하는 방법

 문제 내용 

I have two dictionaries, but for simplification, I will take these two:

저는 두 개의 딕셔너리가 있습니다. 단순화를 위해 이 두 개를 사용하겠습니다:
>>> x = dict(a=1, b=2)
>>> y = dict(a=2, b=2)

 

Now, I want to compare whether each key, value pair in x has the same corresponding value in y. So I wrote this:

이제 x의 각 key, value 쌍이 y에서 해당 값과 일치하는지 비교하려고 합니다. 그래서 이렇게 작성했습니다:
>>> for x_values, y_values in zip(x.iteritems(), y.iteritems()):
        if x_values == y_values:
            print 'Ok', x_values, y_values
        else:
            print 'Not', x_values, y_values

 

And it works since a tuple is returned and then compared for equality.

그리고 이는 튜플을 반환하고 그것이 동등성에 대해 비교되므로 작동합니다.

 

My questions:

질문 사항:

 

Is this correct? Is there a better way to do this? Better not in speed, I am talking about code elegance.

이게 맞나요? 이를 더 좋게하는 방법이 있나요? 속도에 관한 것은 나중에, 코드의 우아함에 대해 얘기하고 있습니다.

 

UPDATE: I forgot to mention that I have to check how many key, value pairs are equal.

업데이트: 몇 개의 key, value 쌍이 일치하는지 확인해야합니다.

 

 

 

 높은 점수를 받은 Solution 

If you want to know how many values match in both the dictionaries, you should have said that :)

두 딕셔너리에서 일치하는 값이 몇 개인지 알고 싶다면 이렇게 말해야합니다 :)

 

Maybe something like this:

아마도 이렇게 할 수 있습니다.
shared_items = {k: x[k] for k in x if k in y and x[k] == y[k]}
print(len(shared_items))

 

 

 가장 최근 달린 Solution 

The easiest way (and one of the more robust at that) to do a deep comparison of two dictionaries is to serialize them in JSON format, sorting the keys, and compare the string results:

두 딕셔너리를 깊게 비교하는 가장 쉬운 방법(그리고 가장 견고한 방법 중 하나)은 JSON 형식으로 직렬화하여 키를 정렬하고 문자열 결과를 비교하는 것입니다:
import json
if json.dumps(x, sort_keys=True) == json.dumps(y, sort_keys=True):
   ... Do something ...

 

 

출처 : https://stackoverflow.com/questions/4527942/comparing-two-dictionaries-and-checking-how-many-key-value-pairs-are-equal

반응형
댓글
공지사항
최근에 올라온 글