def shorten_hostnames(machines):
    keys, values = zip(*list(machines.items()))
values = [v.split('.') for v in values]
for i, s in ((-1, slice(-1)), (0, slice(1, None))):
    while all(values):
        if not len(set(v[i] for v in values)) == 1:
            break
if any(len(v) <= 1 for v in values):
    break
values = [v[s] for v in values]
return {k: '.'.join(v) for k, v in zip(keys, values)}
Remove common elements of hostnames (shorten hostnames) - DRY