Get vertex by property value

I am setting up a network modelling routes for public transport systems.
Every vertex has a string property which is a unique name for that specific location.

Is there a way to access a vertex by its property name instead of its index
v = g.vertex(i)

This might be ambigous since property values are assumed to be non-unique (I think).

I’m currently just using a dictionary, but curious if there is an recommended way to do this.

Thanks

There are two ways to achieve this. The first is using the find_vertex() function that searches for all vertices with a given property map value. However, this function has a O(N) complexity, where N is the number of nodes. This means that it can be inefficient if the search is performed frequently.

The second approach is to perform this lookup quickly, in O(1) time, but it requires the user to keep her own dictionary that maps vertices to property values, e.g.:

   >>> from collections import defaultdict
   >>> g = gt.Graph()
   >>> g.gp.vmap = g.new_gp("object", val=defaultdict(list))
   >>> def add_vertex(g, prop, value):
   ...    v = g.add_vertex()
   ...    prop[v] = value
   ...    g.gp.vmap[value].append(v)
   ...    return g
   >>> name = g.new_vp("string")
   >>> add_vertex(g, name, "bob")
   >>> add_vertex(g, name, "eve")
   >>> add_vertex(g, name, "steve")
   >>> g.gp.vmap["eve"]
   [<Vertex object with index '1' at 0x...>]
1 Like

Exactly what I was looking for. Thank you for this answer!