I need to compare dictionary b against a to check whether the keys of b are in a.
If present check the values of a[key]==b[key]. If not equal print the key:value pair of both dictionaries for reference. How can I do that?
a = {'key_1': 1,'key_2': 2, 'key_3': 3}
b = {'key_1': 1,'key_2': 5}
[k for key in b if key in a if b[k]!=a[k]]
I used the above code, but not able to print both the dictionaries keys and value as like
not equal: b[key_2]=5 and a[key_2]=2
I need to compare dictionary b against a to check whether the keys of b are in a. You want to find the intersecting keys and then check their values:
a = {'key_1': 1,'key_2': 2, 'key_3': 3}
b = {'key_1': 1,'key_2': 5}
# find keys common to both
inter = a.keys() & b
diff_vals = [(k, a[k], b[k]) for k in inter if a[k] != b[k]]
# find keys common to both
inter = a.keys() & b
for k,av, bv in diff_vals:
print("key = {}, val_a = {}, val_b = {}".format(k, av, bv))
key = key_2, val_a = 2, val_b = 5
You can use many different set methods on the dict_view objetcs:
# find key/value pairings that are unique to either dict
symmetric = a.items() ^ b.items()
{('key_2', 2), ('key_2', 5), ('key_3', 3)}
# key/values in b that are not in a
difference = b.items() - a.items()
{('key_2', 5)}
# key/values in a that are not in b
difference = a.items() - b.items()
{('key_3', 3), ('key_2', 2)}
# get unique set of all keys from a and b
union = a.keys() | b
{'key_1', 'key_2', 'key_3'}
# get keys common to both dicts
inter = a.keys() & b
{'key_1', 'key_2'}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With