Answer the question
In order to leave comments, you need to log in
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
You somehow did not set the task very clearly.
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}')
from itertools import islice
print(
list(islice(ddif(a, b), None, 1))
)
Is there a quick way to find this pair?
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 questionAsk a Question
731 491 924 answers to any question