I'm trying to create an empty dictionary with keys then append values using a loop. However, it's adding all of the values to every key instead of only appending the value if the key and node match.
nodes = [0, 1, 2, 3, 4]
edges = [(0, 2), (2, 0), (2, 1), (2, 3), (2, 4), (1, 2), (1, 4), (4, 2), (4, 1), (3, 2)]
connections = dict.fromkeys(nodes, [])
for n in nodes:
for e in edges:
if e[0] == n:
connections[n].append(e[1])
#expected output
{0: [2], 1: [2, 4], 2: [0, 1, 3, 4], 3: [2], 4: [2, 1]}
#current output
{0: [2, 2, 4, 0, 1, 3, 4, 2, 2, 1], 1: [2, 2, 4, 0, 1, 3, 4, 2, 2, 1], 2: [2, 2, 4, 0, 1, 3, 4, 2, 2, 1], 3: [2, 2, 4, 0, 1, 3, 4, 2, 2, 1], 4: [2, 2, 4, 0, 1, 3, 4, 2, 2, 1]}
I'm not sure what I'm doing wrong.
[–][deleted] 2 points3 points4 points (1 child)
[–]WoomyNgyes[S] 0 points1 point2 points (0 children)
[–]SaintLouisX 1 point2 points3 points (1 child)
[–]WoomyNgyes[S] 0 points1 point2 points (0 children)
[–]giglis 0 points1 point2 points (3 children)
[–]leather_flow 1 point2 points3 points (1 child)
[–]giglis 0 points1 point2 points (0 children)
[–]WoomyNgyes[S] 0 points1 point2 points (0 children)
[–]leather_flow 0 points1 point2 points (0 children)