I'm looking for an efficient way to find the intersection of two Python dictionaries where order matters, starting at the top. In other words, loop through the dictionaries and once their keys or values differ, stop. I think this is clearest with some examples.
- The intersection of
{a: 1, b: 0}
and{a: 1, b: 1}
is obviously{a: 1}
. - The intersection of
{a: 1, b: 0, c: 1}
and{a: 1, c: 1, b: 0}
is just{a: 1}
since order matters. - The intersection of
{a: 1, b: 0}
and{b: 0, c: 1}
is empty because they don't start on the same key.
I have the following function which works, but I'm wondering if there's an easier/faster way.
def find_ordered_intersection(d0, d1):
d1keys = list(d1.keys())
intersection = {}
for i, (k, v) in enumerate(d0.items()):
if (k == d1keys[i]) and (v == d1[k]):
intersection.update({k:v})
else:
return intersection
p.s. I'm having a hard time succinctly describing my goal. If anyone has edits, please feel free.