1

Currently I have a very simple graph set up like this:

import networkx as nx

G = nx.Graph()

lat = 40.661
long = -73.944

G.add_node(12345, latlong=(lat, long))

And G.nodes[12345]['latlong'], of course, returns (40.661, -73.944).

What's the best way to set things up so that I also get:

G.nodes[12345]['longlat'] returns (-73.944, 40.661)

G.nodes[(40.661, -73.944)] returns 12345

I know that I could also add nodes like this: G.add_node(12345, latlong=(lat, long), longlat=(long, lat)) and have an extra dictionary d = {(40.661, -73.944): 12345}.

But is there also a nicer, not too hacky, way without duplicating data?

Community
  • 1
  • 1
  • `networkx` is a package for graphs, where you always have to decide which element you want to represent with a node (in your case either the id or the position). Alternatively if you only want to store the information and want to have free access with any information you have, you may want to look for a table (e.g. pandas package), or a database (if you have large datasets). – Sparky05 Mar 25 '20 at 08:54
  • Obviously I need the graph... For now I have added a dictionary, mapping latlong to the ids, and functions to the instance. So these now work: `G.get_id()`, `G.get_latlong()`, `G.get_longlat()`. But not sure whether there is perhaps a REALLY neat way to do this. –  Mar 25 '20 at 09:09
  • Okay, I understand. So you want something like described in this question: https://stackoverflow.com/questions/13336952/2d-dictionary-with-many-keys-that-will-return-the-same-value#comment18199011_13336952 and create your own subclass of `networkx.Graph`, see https://networkx.github.io/documentation/stable/reference/classes/graph.html#overview, where you replace the `dict` with the `AliasDict` – Sparky05 Mar 25 '20 at 09:31

0 Answers0