Search code examples
pythondictionarynetworkx

Create dictionary where values are keys transformed to strings


G is a graph object and sorted(G) returns a list of nodes:

[0,1,2...1860]

I need to rename those nodes mapping from a dictionary, like so:

mapping = {0: "0_cereb", 1: "1_cereb", 2: "2_cereb",..., 1860: "1860_cereb"}

And then I can apply dict to a method that relabels my graph:

import networkx as nx
Gnew = nx.relabel_nodes(G, mapping)

and sorted(Gnew)returns:

[0_cereb, 2_cereb, ..., 1860_cereb]

How do I create this mapping dict?


Solution

  • Use a dictionary comprehension to create the dictionary, and use string formatting to convert the numbers to the corresponding strings.

    mapping = {x: f'{x}_cereb' for x in G}