NetworkX: Adding edges to a graph from a dictionary with lists as values

前提是你 提交于 2020-06-12 17:45:11

问题


I have a question on how to add edges to a graph from a dictionary containing lists as values. I want to define a function that takes a dictionary as an argument and then adding an edge for each key+object in the list of values. I have created the empty graph structure and wonder if there is a smart way to add the entire dictionary.

def build_network(dict):

  G = nx.Graph() 

After that I just want to return the constructed graph.

I know it is a novice question, but any help will be received gratefully!

Edit 1: The dictionary contains of an football player as key and a list of clubs he have been playing in as value.

Edit 2: The string of the dictionary is in Unicode. An example would be {u'Drogba': [u'Le Mans', u'Chelsea', u'Galatasaray'], u'Beckham: [u'Manchester United', u'Real Madrid', u'Los Angeles Galaxy']}


回答1:


The Graph object can take a dictionary as an initialization argument, so I think it'll do what you want pretty straightforwardly:

>>> d = {'Drogba': ['Le Mans', 'Chelsea', 'Galatasaray'], 'Beckham': ['Manchester United', 'Real Madrid', 'Los Angeles Galaxy']}
>>> g = nx.Graph(d)
>>> g.nodes()
['Manchester United', 'Beckham', 'Real Madrid', 'Le Mans', 'Los Angeles Galaxy', 'Drogba', 'Galatasaray', 'Chelsea']
>>> g.edges("Beckham")
[('Beckham', 'Real Madrid'), ('Beckham', 'Los Angeles Galaxy'), ('Beckham', 'Manchester United')]
>>> g.neighbors("Drogba")
['Galatasaray', 'Chelsea', 'Le Mans']


来源:https://stackoverflow.com/questions/26665799/networkx-adding-edges-to-a-graph-from-a-dictionary-with-lists-as-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!