I have two dicts, where the dict inside the dict stands for the values in the other dict:
dict1 = {1:{1,3}, 2:{2}}
dict2 = {1:{5}, 3:{1}}
I am trying to find out, if the combination would result in a loop, for example:
dict1: 1 -> dict2: 3 -> dict1: 1; This would result in a loop, so my script should throw an error.
dict1: 2 -> not in dict2; Not a loop would be okay
dict1: 1 -> dict2: 1 -> 5 not in dict 1; Not a loop would be okay
Any ideas how I could solve that problem? Thanks in advance!
If you just want to know if there is a loop between the two dictionaries you can use this code:
for key, values in dict1.items():
if any([v in dict2 and key in dict2[v] for v in values]):
print('loop found')
Otherwise, if you want to know where the specific loop is, you need to break out the iteration over values in the above code:
for key, values in dict1.items():
for v in values:
if v in dict2 and key in dict2[v]:
print('loop found from ' + str(key) + ' through value ' + str(v) + ' back to ' + str(key))
For your sample data the output is either loop found for the first code snippet or loop found from 1 through value 3 back to 1 for the second.
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