Warning

This documents an unmaintained version of NetworkX. Please upgrade to a maintained version and see the current NetworkX documentation.

# MultiGraph - Undirected graphs with self loops and parallel edges¶

## Overview¶

MultiGraph(data=None, **attr)

An undirected graph class that can store multiedges.

Multiedges are multiple edges between two nodes. Each edge can hold optional data or attributes.

A MultiGraph holds undirected edges. Self loops are allowed.

Nodes can be arbitrary (hashable) Python objects with optional key/value attributes.

Edges are represented as links between nodes with optional key/value attributes.

Parameters : data : input graph Data to initialize graph. If data=None (default) an empty graph is created. The data can be an edge list, or any NetworkX graph object. If the corresponding optional Python packages are installed the data can also be a NumPy matrix or 2d ndarray, a SciPy sparse matrix, or a PyGraphviz graph. attr : keyword arguments, optional (default= no attributes) Attributes to add to graph as key=value pairs.

Examples

Create an empty graph structure (a “null graph”) with no nodes and no edges.

>>> G = nx.MultiGraph()


G can be grown in several ways.

Nodes:

Add one node at a time:

>>> G.add_node(1)


Add the nodes from any container (a list, dict, set or even the lines from a file or the nodes from another graph).

>>> G.add_nodes_from([2,3])
>>> H=nx.Graph()


In addition to strings and integers any hashable Python object (except None) can represent a node, e.g. a customized node object, or even another Graph.

>>> G.add_node(H)


Edges:

G can also be grown by adding edges.

>>> G.add_edge(1, 2)


a list of edges,

>>> G.add_edges_from([(1,2),(1,3)])


or a collection of edges,

>>> G.add_edges_from(H.edges())


If some edges connect nodes not yet in the graph, the nodes are added automatically. If an edge already exists, an additional edge is created and stored using a key to identify the edge. By default the key is the lowest unused integer.

>>> G.add_edges_from([(4,5,dict(route=282)), (4,5,dict(route=37))])
>>> G
{3: {0: {}}, 5: {0: {}, 1: {'route': 282}, 2: {'route': 37}}}


Attributes:

Each graph, node, and edge can hold key/value attribute pairs in an associated attribute dictionary (the keys must be hashable). By default these are empty, but can be added or changed using add_edge, add_node or direct manipulation of the attribute dictionaries named graph, node and edge respectively.

>>> G = nx.MultiGraph(day="Friday")
>>> G.graph
{'day': 'Friday'}


>>> G.add_node(1, time='5pm')
>>> G.node
{'time': '5pm'}
>>> G.node['room'] = 714
>>> del G.node['room'] # remove attribute
>>> G.nodes(data=True)
[(1, {'time': '5pm'}), (3, {'time': '2pm'})]


Warning: adding a node to G.node does not add it to the graph.

>>> G.add_edge(1, 2, weight=4.7 )
>>> G['weight'] = 4.7
>>> G.edge['weight'] = 4


Shortcuts:

Many common graph features allow python syntax to speed reporting.

>>> 1 in G     # check if node in graph
True
>>> [n for n in G if n<3]   # iterate through nodes
[1, 2]
>>> len(G)  # number of nodes in graph
5
>>> G # adjacency dict keyed by neighbor to edge attributes
...            # Note: you should not change this dict manually!
{2: {0: {'weight': 4}, 1: {'color': 'blue'}}}


The fastest way to traverse all edges of a graph is via adjacency_iter(), but the edges() method is often more convenient.

>>> for n,nbrsdict in G.adjacency_iter():
...     for nbr,keydict in nbrsdict.items():
...        for key,eattr in keydict.items():
...            if 'weight' in eattr:
...                (n,nbr,eattr['weight'])
(1, 2, 4)
(2, 1, 4)
(2, 3, 8)
(3, 2, 8)
>>> [ (u,v,edata['weight']) for u,v,edata in G.edges(data=True) if 'weight' in edata ]
[(1, 2, 4), (2, 3, 8)]


Reporting:

Simple graph information is obtained using methods. Iterator versions of many reporting methods exist for efficiency. Methods exist for reporting nodes(), edges(), neighbors() and degree() as well as the number of nodes and edges.

For details on these and other miscellaneous methods, see below.

## Adding and removing nodes and edges¶

 MultiGraph.__init__([data]) Initialize a graph with edges, name, graph attributes. MultiGraph.add_node(n[, attr_dict]) Add a single node n and update node attributes. MultiGraph.add_nodes_from(nodes, **attr) Add multiple nodes. MultiGraph.remove_node(n) Remove node n. MultiGraph.remove_nodes_from(nodes) Remove multiple nodes. MultiGraph.add_edge(u, v[, key, attr_dict]) Add an edge between u and v. MultiGraph.add_edges_from(ebunch[, attr_dict]) Add all the edges in ebunch. MultiGraph.add_weighted_edges_from(ebunch[, ...]) Add all the edges in ebunch as weighted edges with specified weights. MultiGraph.remove_edge(u, v[, key]) Remove an edge between u and v. MultiGraph.remove_edges_from(ebunch) Remove all edges specified in ebunch. MultiGraph.add_star(nodes, **attr) Add a star. MultiGraph.add_path(nodes, **attr) Add a path. MultiGraph.add_cycle(nodes, **attr) Add a cycle. MultiGraph.clear() Remove all nodes and edges from the graph.

## Iterating over nodes and edges¶

 MultiGraph.nodes([data]) Return a list of the nodes in the graph. MultiGraph.nodes_iter([data]) Return an iterator over the nodes. MultiGraph.__iter__() Iterate over the nodes. MultiGraph.edges([nbunch, data, keys]) Return a list of edges. MultiGraph.edges_iter([nbunch, data, keys]) Return an iterator over the edges. MultiGraph.get_edge_data(u, v[, key, default]) Return the attribute dictionary associated with edge (u,v). MultiGraph.neighbors(n) Return a list of the nodes connected to the node n. MultiGraph.neighbors_iter(n) Return an iterator over all neighbors of node n. MultiGraph.__getitem__(n) Return a dict of neighbors of node n. MultiGraph.adjacency_list() Return an adjacency list representation of the graph. MultiGraph.adjacency_iter() Return an iterator of (node, adjacency dict) tuples for all nodes. MultiGraph.nbunch_iter([nbunch]) Return an iterator of nodes contained in nbunch that are also in the graph.