I am trying to remove all non-matching items (values with different keys) in two dicts dict_a and dict_b. What is a better way of achieving this?
Example:
d1 = {key1: x1, key2: y1, key4: z1}
d2 = {key1: x2, key3: y2, key4: w1}
# becomes:
# d1 = {key1: x1, key4: z1}
# d2 = {key1: x2, key4: w1}
My attempt:
keep_keys = [keyA for keyA in dict_a.keys() if keyA in dict_b.keys()]
for i in dict_b.copy().keys():
if i not in keep_keys:
del dict_b[i]
for i in dict_a.copy().keys():
if i not in keep_keys:
del dict_a[i]
I am looking for shorter (pythonic) way of doing this.
>Solution :
You can do:
d1 = {"key1": "x1", "key2": "y1", "key4": "z1"}
d2 = {"key1": "x2", "key3": "y2", "key4": "w1"}
common_keys = d1.keys() & d2.keys()
d1 = {k: d1[k] for k in common_keys}
d2 = {k: d2[k] for k in common_keys}
print(d1)
print(d2)
Prints:
{'key1': 'x1', 'key4': 'z1'}
{'key1': 'x2', 'key4': 'w1'}