Marine Galantin
Marine Galantin

Reputation: 2279

Sorting a dictionary and then replace the values by ranking

I have a dictionary (representing the values for all the nodes of a graph) and I would like to replace it by the ranking of each point in this dictionary.

It looks like this:

I am taking the value from:

A = nx.degree_centrality(G)

giving:

A := {0: 0.0012082158679017317, 1: 0.002013693113169553, 2: 0.002013693113169553, 3: 0.0012082158679017317,...

I did this:

Abis = {k: v for k, v in sorted(A.items(), key=lambda item: item[1], reverse=True)}

getting

Abis := {1244: 0.06766008860249698, 270: 0.031413612565445025, 1562: 0.029802658074909383,...

Now, I have no idea how to create Atiers such that, I get:

Atiers := {1244: 1, 270: 2, 1562: 3,...

I would like to create a new dictionary from Abis such that I can get the ranking following this criteria.

If you have any idea how you can do this directly from A, I would also be happy with that. I am thinking about it for an hour with success.

Upvotes: 1

Views: 283

Answers (2)

Vicrobot
Vicrobot

Reputation: 3988

You can try enumerate:

Atiers = {k: i for i, (k,v) in enumerate(sorted(A.items(), key=lambda item: item[1], reverse=True), start = 1)}

Upvotes: 2

asafpr
asafpr

Reputation: 357

Atiers = {}
for (i, k) in enumerate(Abis.keys()):
   Atiers[k] = i

Upvotes: 0

Related Questions