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']}
CodePudding user response:
Unless one of the students is related to Little Bobby Tables, maybe just add newlines to the string representation:
print(str(ansdict).replace('],', '],\n'))
CodePudding user response:
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()]))
CodePudding user response:
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])