-1

So I'm trying to find indirect relations in a dictionary but I can't seem to find a general code for my program: this is what I have

#find if A is related to E
data = {"A": {"B": 5, "C": 7}, "B": {"E": 8}, "C": {}, "D": {}, "E": {"D": 9}}
if "E" in data["A"]:
    result = True
if "E" in data["B"] or "D" in data["C"]:
    result = True
else:
    result = False
print(result)
#output = True because "E" is in data["A"]

For this one example it works and ofcourse I've could generalize this with x's and y's but if I have a data variable with a complexer dictionary it wouldn't work. Maybe recursive code or a for loop? If somebody could help, it would be very much appreciated.

Thank you in advance

TheCreator
  • 155
  • 6

2 Answers2

1
for k,v in data.items():
    for l,u in data.items():
        if k in u:
            print(f"{k} in {u}")

so that the desired function might be :

def has_indirect_rel(dico):
    for k,v in dico.items():
        for l,u in dico.items():
            if k in u: return True
    return False
smed
  • 148
  • 1
  • 10
  • If we're trying to answer the question, "find if A is related to E" then this will return `True` with data `{"A": {"B", "C"}, "C": {}}` that doesn't even have E! It only answers the question, is there *any* indirect relationship in the data. – cdlane Dec 12 '20 at 17:13
0

First, the numbers aren't of interest to the problem at hand, so let's reduce the data from dict of dictionaries to dict of sets:

data = {'A': {'B', 'C'}, 'B': {'E'}, 'C': {}, 'D': {}, 'E': {'D'}}

We could search the data recursively:

def has_relation(mapping, a, b):
    if b in mapping[a]:
        return True

    for c in mapping[a]:
        if has_relation(mapping, c, b):
            return True

    return False

print(has_relation(data, 'A', 'D'))
print(has_relation(data, 'A', 'E'))
print(has_relation(data, 'A', 'F'))
cdlane
  • 40,441
  • 5
  • 32
  • 81