Construct the tree from a list of edges I was using the following code to construct the tree from a list of nodes: [1, 2] means that there is a bi-directional link between 1 and 2

def createTreeFromEdges(edges):
    tree = {}
    for i in edges:
        v1, v2 = i
        if v1 in tree:
            tree[v1].append(v2)
        else:
            tree[v1] = [v2]

        if v2 in tree:
            tree[v2].append(v1)
        else:
            tree[v2] = [v1]

    return tree


and it works in the following fashion:

edges = [[2, 1], [3, 2], [4, 2], [5, 1], [6, 1], [7, 1], [8, 7]]
print createTreeFromEdges(edges)


This is cool, but for a python it looks like too much code. Is there a way to make it shorter?
The following is very Pythonic, but a little too terse if you are not used to it:

def createTreeFromEdges(edges):
    tree = {}
    for v1, v2 in edges:
        tree.setdefault(v1, []).append(v2)
        tree.setdefault(v2, []).append(v1)
    return tree


Basically, setdefault does the following:

def setdefault(self, key, default=None):
    if key not in self:
        self[key] = default
    return self[key]