I am trying to go through all elements of two given dictionaries to make sure they are equal, and if not I want the name of the property where they differ.
Here is my basic approach:
# Dictionnaries
v1 = { "a" : { "b" : 1, "c" : 2 }, "d" : { "e" : { "f" : 3 }}}
v2 = { "a" : { "b" : 1, "c" : 2 }, "d" : { "e" : { "f" : 4 }}}
def gen(k, v):
if type(v) is dict:
for k in v:
yield from gen(k, v[k])
else:
yield k, v
# Used alone the generator works as expected:
for k, v in gen("root", v1):
print("{}: {}".format(k, v))
My problem is that I want to compare the two dictionaries, from what I could gather it should look like this:
for k1, v1, k2, v2 in zip(gen("root1", v1), gen("root2", v2)):
print("{}: {}".format(k1, v1))
print("{}: {}".format(k2, v2))
print("===========")
The interpreter says only two values are returned, so I assumed this would work (and it does):
for t1, t2 in zip(gen("root1", v1), gen("root2", v2)):
print("{}: {}".format(t1[0], t1[1]))
print("{}: {}".format(t2[0], t2[1]))
print("===========")
My question:
It might be purely preferential, but I really wonder
- How I can get the first loop to work, so that I don't have to use the brackets all the time?
- I tried to unpack with
*
, but no success. Why can't I dozip(*gen(...), *gen(...))
?
(By the way I know I could just add k1, v1, k2, v2 = *t1, *t2
at the beginning of the loop, I'm just looking for a nicer solution)