user3467226
user3467226

Reputation: 81

creating dictionaries to list order of ranking

I have a list of people and who controls who but I need to combine them all and form several sentences to compute which person control a list of people.

The employee order comes from a txt file:

Upvotes: 0

Views: 78

Answers (1)

Matthew Trevor
Matthew Trevor

Reputation: 14961

from collections import defaultdict

controls = defaultdict(list)

with open('data.txt') as file:
    for line in file:
        controller, controlled = line.strip().split(' controls ')
        controls[controller].append(controlled)

print 'employee order:'
for controller, controlled in controls.iteritems():       
    if len(controlled) > 1:
        conjoined = ', '.join(controlled[:-1])
        conjoined = '{} and {}'.format(conjoined, controlled[-1])
    else:
        conjoined = controlled[0]
    print '{} controls {}'.format(controller, conjoined)

Upvotes: 1

Related Questions