D
D
Danil Samodurov2020-06-09 18:54:47
Python
Danil Samodurov, 2020-06-09 18:54:47

How to display different (key, value) of one dictionary from another dictionary?

Hello. I have two large dictionaries. The keys of both dictionaries are the same, but the same keys may have different values. The task is to find different pairs (key, value) from the second dictionary. Is there a quick way to find this pair?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Andrey Leonov, 2020-06-09
@samodurOFF

there is this, you can try dictdiffer

S
Sergey Pankov, 2020-06-09
@trapwalker

You somehow did not set the task very clearly.

  1. The following important details need to be clarified:
  2. Can a different pair have a different key and value individually?
  3. Are the key sets the same? Not the same? May differ?
  4. Are the values ​​hashable?
  5. Does the number of pairs match, or may one pair be missing in one of the dictionaries?
  6. One and only one pair?
  7. What version of Python? If the third, then the dictionaries are equally ordered by key? Maybe they are also sorted? Well, not much...
  8. How big are the dictionaries? Their size is comparable to the total amount of memory?
  9. Your task looks like it makes sense to solve it in a slightly different place and at a different time (in the sense of forming a data structure and filling them). Explain why such a task arose, perhaps there is another, more elegant and efficient approach than comparing large dictionaries.

It looks like this would work for you:
import typing

def ddif(a: dict, b: dict) -> typing.Iterable[tuple]:
    return filter(None, (None if va == b[k] else (k, va, b[k]) for k, va in a.items()))

a = {1: 11, 2: 22, 3: [1, 2, 3], 4: 44, 5: 55}
b = {1: 11, 2: 22, 3: [1, 2, 4], 4: 44, 5: 56}
for k, v1, v2 in ddif(a, b):
    print(f'{k}: {v1!r} != {v2!r}')

It returns an iterator, so if you're sure there's only one difference, you can use islice to stop at the first difference:
from itertools import islice
print(
    list(islice(ddif(a, b), None, 1))
)

G
galaxy, 2020-06-09
@galaxy

Is there a quick way to find this pair?

Fast for a computer or for a programmer?
So, if in one line:
a = {'1': 1, '3': 3, '2': 2, '5': 5, '4': 4, '7': 0, '6': 6, '9': 9, '8': 8}
b = {'3': 3, '2': 2, '5': 5, '4': 16, '7': 7, '6': 6, '9': 9, '8': 8}

set(a.items()) ^ set(b.items())
# set([('4', 4), ('1', 1), ('7', 7), ('4', 16), ('7', 0)])

set(a.items()) - set(b.items())
# set([('1', 1), ('4', 4), ('7', 0)])

set(b.items()) - set(a.items())
# set([('7', 7), ('4', 16)])

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question