Home > database >  Create dictionary where values are keys transformed to strings
Create dictionary where values are keys transformed to strings

Time:02-06

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?

CodePudding user response:

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}

CodePudding user response:

The answer would be dict comprehension

mapping = {k: f"{k}_cereb" for k in sorted(G)}

will run through list and create key value pairs

  •  Tags:  
  • Related