1

i want to add dict on specific key but if there is already a dict on that key then it should append the dict on that specific key like this

graph = {
1:{2:3,3:4,4:7},
2:{3:1,6:5},
3:{6:6,4:2},
4:{5:3,7:6},
5:{7:3,8:4},
6:{5:1,8:8},
7:{8:2},
8:{7:2}
}

This is the format i want and i am using loop as,

graph= {}

def addEdge(u,v):
        graph[u].append(v)

def add(key, value): 
    dic = {}
    dic[key]=value
    return dic
for i in range(0,20):
    a=yy[i]
    b=add(zz[i],xdist[i])
    addEdge(a,b)

I am getting this error

 graph[u].append(v)

KeyError: 1

Values are

a
Out[12]: 1

b
Out[13]: {2: 803}

graph
Out[14]: {}

I can not use graph[a] = b in for loop because as node 1 is connected to more than 1 node so in first iteration it adds dict 2:803 on key 1 and when it comes that 1 is also connected to 12 it over writes 2:803 I do not know how to append it.

Thanks in advance

1 Answers1

2

You should check if the key is present in graph dict or not:

graph = {}
def addEdge(u, v):
    if u in graph.keys():
        graph[u].append(v)
    else:
        graph[u] = [v] #or graph[u] = v

OR

graph = {}
def addEdge(u, v):
    if u in graph.keys():
        graph[u].update(v)
    else:
        graph[u] = v
Vaibhav Jadhav
  • 2,020
  • 1
  • 7
  • 20