Python - directed edge list to dictionary of dictionaries
Question: I have a list of directed edges in a file in the form

    
    
    Source_Id  Target_Id    Edge_Type
    A          B            Train
    A          C            Bus
    B          D            Bus
    C          A            Train
    ...        ...
    

I would like to structure the data in a dictionary of dictionaries such as:

    
    
    {'A': {'B': 'Train', 'C': 'Bus'}, 'B': {'D': 'Bus'}, 'C': {'A': 'Train'}}
    

What is the best way to do that?


Answer: Use a
[`collections.defaultdict()`](http://docs.python.org/2/library/collections.html#collections.defaultdict)
object to materialize the values for you:

    
    
    from collections import defaultdict
    import csv
    
    graph = defaultdict(dict)
    
    with open('inputfile', 'rb') as infh:
        reader = csv.reader(infh, delimiter='\t')
        next(reader, None)  # skip header
    
        for source, target, edge in reader:
            graph[source][target] = edge
    

This assumes there is only one edge between each source and target, and that
the inputfile is tab delimited.

If there are multiple edges, build a list of edge names instead:

    
    
    graph = defaultdict(lambda: defaultdict(list))
    
    with open('inputfile', 'rb') as infh:
        reader = csv.reader(infh, delimiter='\t')
        next(reader, None)  # skip header
    
        for source, target, edge in reader:
            graph[source][target].append(edge)
    

giving you

    
    
    {'A': {'C': ['Bus'], 'B': ['Train']}, 'C': {'A': ['Train']}, 'B': {'D': ['Bus']}}
    

where the edge lists can then represent more edge names.

