9

I'm beginner to programming and I'm new here, so hello!

I'm having a problem with nodes order in networkX. This code:

letters = []
G = nx.Graph()
for i in range(nodesNum):
    letter = ascii_lowercase[i]
    letters.append(letter)
    print letters

G.add_nodes_from(letters)
print "G.nodes  = ", (G.nodes())

returns this:

['a']
['a', 'b']
['a', 'b', 'c']
['a', 'b', 'c', 'd']
['a', 'b', 'c', 'd', 'e']
['a', 'b', 'c', 'd', 'e', 'f']
['a', 'b', 'c', 'd', 'e', 'f', 'g']
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
G.nodes  =  ['a', 'c', 'b', 'e', 'd', 'g', 'f', 'i', 'h', 'j']

While I would like to have it in normal (alphabetical) order. Could anyone tell me what am I doing wrong? The order is important to me, as later I'm asking user to tell me where the edges are.

Thanks in advance!

dreptak
  • 193
  • 4
  • 10
  • 2
    See http://stackoverflow.com/questions/15479928/why-is-the-order-in-python-dictionaries-and-sets-arbitrary for more information about why this is happening. NetworkX uses a python dict to store the nodes. – Joel Mar 07 '16 at 02:56

2 Answers2

6

You can sort the nodes on output like this

print "G.nodes  = ", sorted(G.nodes())

or similarly you can sort the edges like

print "G.edges = ", sorted(G.edges())
Joel
  • 22,598
  • 6
  • 69
  • 93
Aric
  • 24,511
  • 5
  • 78
  • 77
2

Aric's solution would do fine if you want to use this for printing only. However if you are going to use adjacent matrix for calculations and you want consistent matrices in different runs, you should do:

letters = []
G = nx.OrderedGraph()
for i in range(10):
    letter = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'][i]
    letters.append(letter)
    print (letters)

G.add_nodes_from(letters)
print ("G.nodes  = ", (G.nodes()))

which returns

['a']
['a', 'b']
['a', 'b', 'c']
['a', 'b', 'c', 'd']
['a', 'b', 'c', 'd', 'e']
['a', 'b', 'c', 'd', 'e', 'f']
['a', 'b', 'c', 'd', 'e', 'f', 'g']
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
G.nodes  =  ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
ozgeneral
  • 6,079
  • 2
  • 30
  • 45