visited_ids = set()
for node_a_id in nodes:
    for node_b_id in nodes[node_a_id]:
        if nod_b_id == node_a_id:
            raise ValueError
if node_b_id in visited_ids:
    continue
for node_c_id in nodes[node_b_id]:
    if node_c_id in visited_ids:
        continue
if node_a_id in nodes[node_c_id]:
    yield node_a_id, node_b_id, node_c_id
visited_ids.add(node_a_id)
Finding cycle of 3 nodes ( or triangles) in a graph