# Code:networkx

The networkx library is a great tool for quick graph operations in python put together by the wonderful folks at Los Alamos National Labs. It uses a representation based on dictionaries of dictionaries.

A dictionary of sets is simpler, so I'll show that too. For both representations, each node is a dictionary key, and the value stores the names of its child nodes. So, a graph with nodes 1,2,3 connected in a triangle would look like:

<source lang="python"> G = {1: {2,3}, 2: {1,3}, 3: {1,2} } # dict-of-sets G = {1: {2:1,3:1}, 2: {1:1,3:1}, 3: {1:1,2:1} } # dict-of-dicts </source> The {1, 2, 3} notation means create a set, while {1:1, 2:2, 3:3} means create a dictionary.

To test whether a node, u is parent to a node v, we can just write, <source lang="python"> def is_child(G, u, v):

```   return v in G[u] # both formats
```

</source>

To add a node to a tree, I would need to create a new key in the dictionary -- like so: <source lang="python"> def add_node(G, u):

```   assert u not in G
G[u] = set() # dict-of-sets
```

```   assert u not in G
G[u] = {} # dict-of-dicts
```

</source>

To put in parent-child edges, I have to add members to the right set, <source lang="python"> def add_children(G, u, kids):

```   G[u] += kids # dict-of-set
```

```   k,v in kids.iteritems(): # dict-of-dict
```

G[u][k] = v

1. e.g.