Home > front end >  need to print an output using dictionary
need to print an output using dictionary

Time:12-08

I have a dictionary that looks like this:

{'ACC210': ['Luther, Martin', 'Spurgeon, Charles'], 'CS121P': ['Bunyan, John', 'Henry, Matthew', 'Luther, Martin'], 'CS132S': ['Calvin, John', 'Knox, John', 'Owen, John']}

I need to be able to make an output that looks like this:

Luther, Martin: ACC210 CS121P
Spurgeon, Charles: ACC210
Bunyan, John: CS121P
Henry, Matthew: CS121P
Calvin, John: CS132S
Knox, John: CS132S
Owen, John: CS132S

How would I do that?

CodePudding user response:

Your dictionary structure is oriented the wrong way to do this easily, so the first step is going to reverse it.

Assuming the following:

d = {
    'ACC210': ['Luther, Martin', 'Spurgeon, Charles'],
    'CS121P': ['Bunyan, John', 'Henry, Matthew', 'Luther, Martin'],
    'CS132S': ['Calvin, John', 'Knox, John', 'Owen, John']
}

This snippet will output what you expect

    new_d = {}
    for key, value in d.items():
        for name in value:
            if name in new_d:
                new_d[name].append(key)
            else:
                new_d[name] = [key]

    for key, value in new_d.items():
        print(key, ':', ''.join(value))
  • Related