How to add new lines inside a dictionary?

Question:

I want to print out each key on a different line in the dictionary, but don’t know how. The assignment I’m tackling doesn’t allow loop statements, so printing each line individually using for loop is out of the question. Please help

So this is my code

students = ['Tommy', 'Kitty', 'Jessie', 'Chester', 'Curie', 'Darwing', 'Nancy', 'Sue', 
            'Peter', 'Andrew', 'Karren', 'Charles', 'Nikhil', 'Justin', 'Astha', 'Victor', 
            'Samuel', 'Olivia', 'Tony']

assignment = [2, 5, 5, 7, 1, 5, 2, 7, 5, 1, 1, 1, 2, 1, 5, 2, 7, 2, 7]

groupset=set(assignment)    
sorted_list=sorted(list(groupset)) 
ansdict={}
ansdict={f'Group {a}':[students[b] for b in range(len(students)) if assignment[b] == a] for a in sorted_list}
print(ansdict)

and the output is

{'Group 1': ['Curie', 'Andrew', 'Karren', 'Charles', 'Justin'], 'Group 2': ['Tommy', 'Nancy', 'Nikhil', 'Victor', 'Olivia'], 'Group 5': ['Kitty', 'Jessie', 'Darwing', 'Peter', 'Astha'], 'Group 7': ['Chester', 'Sue', 'Samuel', 'Tony']}

when I want it to be

{'Group 1': ['Curie', 'Andrew', 'Karren', 'Charles', 'Justin'],
 'Group 2': ['Tommy', 'Nancy', 'Nikhil', 'Victor', 'Olivia'],
 'Group 5': ['Kitty', 'Jessie', 'Darwing', 'Peter', 'Astha'],
 'Group 7': ['Chester', 'Sue', 'Samuel', 'Tony']}
Asked By: Gartz man

||

Answers:

prints = [print(f'{key}: {value}') for key, value in ansdict.items()]

Edit: Less janky alternative

print('n'.join([f'{key}: {value}' for key, value in ansdict.items()]))
Answered By: Michael Cao
sorted_list=sorted(list(groupset)) 

ansdict={}
ansdict={f'Group {a}':[students[b] for b in range(len(students)) if assignment[b] == a] for a in sorted_list}

for key in ansdict.keys():
    print(key,ansdict[key])
Answered By: mostafa sami

Unless one of the students is related to Little Bobby Tables, maybe just add newlines to the string representation:

print(str(ansdict).replace('],', '],n'))
Answered By: Kelly Bundy
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.