Hello!
python-igraph
does not have a direct constructor yet for the dictionary-of-lists representation but it’s an easy one-liner to cast it into a list-of-pairs representation and then you can use Graph.TupleList()
:
adjlist = {"a": ["b", "c", "d"], "b": ["d"], "e": ["a"]}
pairs = sum(([(source, target) for target in targets] for source, targets in adjlist.items()), [])
g = Graph.TupleList(pairs)
print(g.vs["name"])
print(g.get_edgelist())
now my nodes are represented by numbers instead of text. Is there a way to search for a text since all my nodes are now numbers?
Vertices in an igraph graph always have numeric identifiers from 0 to |V|-1; this is because igraph is rooted in C where it is much easier to work with contiguous ranges of numbers than arbitrary strings. Typically, the string names of the vertices are stored in the name
vertex attribute of the graph, which you can retrieve with:
g.vs["name"]
This gives you a list where the i-th element is the name of the i-th node. You can turn this into a lookup table if you need the reverse mapping:
>>> name_to_index = {v: k for k, v in enumerate(g.vs["name"])}
>>> print(name_to_index)
{'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4}
However, in 99% of the cases you won’t need the mapping because any python-igraph
function that needs a vertex ID can also accept a name instead, and it will automatically look up the ID of the vertex behind a scenes (and it cache a mapping similar to the one I constructed manually above). E.g., in the example graph from my first code snippet, you can get the degree of node c
as follows:
>>> g.degree("c")
1
This is the same as referring to the node by its index:
>>> g.degree("c") == g.degree(2)
True