def _toposort(edges):
 incoming_edges = reverse_dict(edges)
 incoming_edges = dict(((k, set(val)) for (k, val) in iteritems(incoming_edges)))
 S = set((v for v in edges if (v not in incoming_edges)))
 L = []
 while S:
  n = S.pop()
  L.append(n)
  for m in edges.get(n, ()):
   assert (n in incoming_edges[m])
   incoming_edges[m].remove(n)
   if (not incoming_edges[m]):
    S.add(m)
 if any((incoming_edges.get(v, None) for v in edges)):
  raise ValueError('Input has cycles')
 return L

def _toposort ( edges ) : incoming_edges = reverse_dict ( edges ) incoming_edges = dict ( ( ( k , set ( val ) ) for ( k , val ) in iteritems ( incoming_edges ) ) ) S = set ( ( v for v in edges if ( v not in incoming_edges ) ) ) L = [ ] while S : n = S . pop ( ) L . append ( n ) for m in edges . get ( n , ( ) ) : assert ( n in incoming_edges [ m ] ) incoming_edges [ m ] . remove ( n ) if ( not incoming_edges [ m ] ) : S . add ( m ) if any ( ( incoming_edges . get ( v , None ) for v in edges ) ) : raise ValueError ( 'Input has cycles' ) return L
dependencies are expressed as a dictionary whose keys are items and whose values are a set of dependent items .