Python adding data in multi-dimensional dictionary -


while (e > 0):     line = raw_input("enter edges : ")     data = line.split()     mygraph[data[0]] = {data[1] : data[2]} //this line      print mygraph     e-=1 

desired data structure:

mygraph = {          'b': {'a': 5, 'd': 1, 'g': 2}         'a': {'b': 5, 'd': 3, 'e': 12, 'f' :5}} 

i want add multiple entries same key mycode taking 1 value 1 node , replacing entries.how that?

you need first add empty dictionary key data[0] if doesn't exist, add values it. otherwise wipe out out every time loop.

the 2 usual ways either use setdefault on normal dictionary:

mygraph.setdefault(data[0], {})[data[1]] = data[2] 

or use collections.defaultdict default empty dictionary:

>>> collections import defaultdict  >>> mygraph = defaultdict(dict)  >>> edges = [[1, 2, 3], [1, 3, 6]] >>> edge in edges: ...     mygraph[edge[1]][edge[2]] = edge[3]  >>> mygraph {1: {2: 3,      3: 6}} 

Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -