问题
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