def remove_common_prefix(*parts):
    zipped = zip_longest(fillvalue=None, *(p[:-1] for p in parts))
stripped = dropwhile(lambda v: len(set(v)) == 1, zipped)
res = [([_f for _f in part if _f] + (old[-1],)) for part, old in zip(zip(*stripped
    ), parts)]
return res or [p[-1:] for p in parts]

def shorten_hostnames(machines):
    if len(machines) == 1:
        return {k: v.split('.', 1)[0] for k, v in list(machines.items())}
keys, values = zip(*list(machines.items()))
parts = remove_common_prefix(*(v.split('.')[::-1] for v in values))
parts = remove_common_prefix(*(part[::-1] for part in parts))
return {k: '.'.join(v) for k, v in zip(keys, parts)}
Remove common elements of hostnames (shorten hostnames) - DRY