Reputation: 1
I've faced a few problems in the process of Binary Graph dev.
So far my problem is an unstable list of nodes. Once I add nodes the output list is totally reordered.
Below is my output.
Has anyone faced such a problem before?
g.node.items()
[(8, {'location': 'root'}), (9, {'location': 'right'}), (5, {'location': 'left'}), (15, {'location': 'right'})]
g.add_node(12, location='left')
g.node.items()
[(8, {'location': 'root'}), (9, {'location': 'right'}), (12, {'location': 'left'}), (5, {'location': 'left'}), (15, {'location': 'right'})]
g.add_node(6, location='right')
g.node.items()
[(5, {'location': 'left'}), (6, {'location': 'right'}), (8, {'location': 'root'}), (9, {'location': 'right'}), (12, {'location': 'left'}), (15, {'location': 'right'})]
Upvotes: 0
Views: 53
Reputation: 366133
Assuming g
is a networks.Graph
or one of the three similar types, node
is a dictionary of nodes. That's only implied by the documentation, but in the source, you can see directly that it's a standard Python dict
.
As the documentation says, dict.items()
returns a view on the items "in an arbitrary order which… varies across Python implementations, and depends on the dictionary's history of insertions and deletions."
(If you're using Python 2.x, there's no "view", just a list of pairs, but the docs use the exact same wording for the arbitrary order of those pairs.)
So, this is exactly what you should expect. items()
gives you the items in an arbitrary order, which changes after an insertion.
If you need to keep track of the order of insertion, you normally use collections.OrderedDict
for that, or manually keep track of them separately. If you want them in some other order, like sorted, you similarly need to use a different type or do that manually.
Upvotes: 1