summaryrefslogtreecommitdiff
path: root/networkx/relabel.py
diff options
context:
space:
mode:
authorDan Schult <dschult@colgate.edu>2020-12-19 20:09:27 -0500
committerGitHub <noreply@github.com>2020-12-19 17:09:27 -0800
commit8585169fe5c34dbab9c57036912d5e5446548ab6 (patch)
tree3374437d8aef38d5e02594bc4ac3a19f8da3e55e /networkx/relabel.py
parent36ecc3c7d40e94f52121dffeac0d621fe191f7ea (diff)
downloadnetworkx-8585169fe5c34dbab9c57036912d5e5446548ab6.tar.gz
Allow relabel_nodes mapping to have non-node keys that get ignored (#4466)
Any keys in mapping that are not nodes in the graph are now ignored instead of raising a KeyError
Diffstat (limited to 'networkx/relabel.py')
-rw-r--r--networkx/relabel.py8
1 files changed, 4 insertions, 4 deletions
diff --git a/networkx/relabel.py b/networkx/relabel.py
index 068b1653..b5066155 100644
--- a/networkx/relabel.py
+++ b/networkx/relabel.py
@@ -14,6 +14,7 @@ def relabel_nodes(G, mapping, copy=True):
mapping : dictionary
A dictionary with the old labels as keys and new labels as values.
A partial mapping is allowed. Mapping 2 nodes to a single node is allowed.
+ Any non-node keys in the mapping are ignored.
copy : bool (optional, default=True)
If True return a copy, or if False relabel the nodes in place.
@@ -88,6 +89,7 @@ def relabel_nodes(G, mapping, copy=True):
Notes
-----
Only the nodes specified in the mapping will be relabeled.
+ Any non-node keys in the mapping are ignored.
The keyword setting copy=False modifies the graph in place.
Relabel_nodes avoids naming collisions by building a
@@ -144,16 +146,14 @@ def _relabel_inplace(G, mapping):
directed = G.is_directed()
for old in nodes:
+ # Test that old is in both mapping and G, otherwise ignore.
try:
new = mapping[old]
+ G.add_node(new, **G.nodes[old])
except KeyError:
continue
if new == old:
continue
- try:
- G.add_node(new, **G.nodes[old])
- except KeyError as e:
- raise KeyError(f"Node {old} is not in the graph") from e
if multigraph:
new_edges = [
(new, new if old == target else target, key, data)