from functools import reduce
def toposort2(data):
    for k, v in list(data.items()):
        v.discard(k)
extra_items_in_deps = reduce(set.union, list(data.values())) - set(data.keys())
data.update({item: set() for item in extra_items_in_deps})
while True:
    ordered = set(item for item, dep in list(data.items()) if not dep)
if not ordered:
    break
for x in sorted(ordered):
    yield x
data = {item: (dep - ordered) for item, dep in list(data.items()) if item not in
    ordered}
if data:
    raise ValueError('a cyclic dependency exists')

def toposort_wrap(data):
    dep_dict = {}
for d in data:
    for bef in d.get('before', ()):
        dep_dict.setdefault(bef, set()).add(d['value'])
dep_dict.setdefault(d['value'], set()).update(d.get('after', ()))
print(dep_dict)
result = list(toposort2(dep_dict))
return result
Построение списка из позиционных отношений между элементами