I am trying to add edges between the cities and dictionary with the distance between them. When I try to compile the code I get to this error, can anyone help me?
import networkx as nx
cities = nx.Graph()
cities.add_edge('San Diego','LA',{'distance':0.4})
cities.add_edge('NY','Nashville',{'distance':5.6})
cities.add_edge('Boston','DC',{'distance':0.8})
I believe your code will work in.networkx 2.0 (it seems to work for me), but not in.networkx 1.11.
In reading through the documentation for.networkx 1.11, it looks like you need to do either
cities.add_edge('Boston', 'Nashville', distance=0.4)
or
cities.add_edge('Boston', 'Nashville', attr_dict = {'distance':0.4})
But I can't easily test it on my machine which has v2.0.
If you want to use a dictionary for attributes then you can do it with @Joel second example
cities.add_edge('Boston', 'Nashville', attr_dict = {'distance':0.4})
however in this case you will get 'attr_dict' as an attribute in which you will have your dictionary. Like this.
cities.edges(data=True)
will return
EdgeDataView([('Boston', 'Nashville', {'attr_dict': {'distance': 0.4}})])
A way to get only your dictionary in attributes is add_edges_from()
:
cities.add_edges_from([('San Diego','LA',{'distance':0.4})])
cities.add_edges_from([('NY','Nashville',{'distance':5.6}),
('Boston','DC',{'distance':0.8})])
cities.edges(data=True)
will return
EdgeDataView([('San Diego', 'LA', {'distance': 0.4}), ('NY', 'Nashville', {'distance': 5.6}), ('Boston', 'DC', {'distance': 0.8})])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.