I need to write the key and value pairs in the dictionary.

But the keys have the same values ​​and the program erases the previous value, but I need all the entries to be present.

What should I do?

There is a fragment:

result = get_sports(["Ронни О'Салливан - снукер", 'Магнус Карлсен - шахматы', 'Марк Селби - снукер']) for key in sorted(result): print(key + ':', ', '.join(sorted(result[key]))) 

It is necessary after the processing procedure to obtain:

 снукер: Марк Селби, Ронни О'Салливан шахматы: Магнус Карлсен 

Thank you very much! It helped! Adapted to the function. There is only one problem left. My code

 def get_sports(lines): result=dict() for sport in lines: item = sport.split('-') result[item[1].strip()] = result.setdefault(item[1].strip(), list()) + [item[0].strip()] return result print(get_sports(['спортсмен1 - спорт1'])) 

displays

{'sport1': ['athlete1']}

and required

{'sport1': {'athlete1'}}

How to get braces instead of square brackets? otherwise the test fails

  • Obviously, use list as value - andreymal

1 answer 1

 sports = ["Ронни О'Салливан - снукер", 'Магнус Карлсен - шахматы', 'Марк Селби - снукер'] dictionary = dict() for sport in sports: item = sport.split('-') dictionary[item[1].strip()] = dictionary.setdefault(item[1].strip(), list()) + [item[0].strip()] for sport, names in dictionary.items(): print('{0}: {1}'.format(sport, ', '.join(names))) 

set() instead of list() :

 sports = ["Ронни О'Салливан - снукер", 'Магнус Карлсен - шахматы', 'Марк Селби - снукер'] dictionary = dict() for sport in sports: item = sport.split('-') dictionary[item[1].strip()] = dictionary.setdefault(item[1].strip(), set()) dictionary[item[1].strip()].add(item[0].strip()) for sport, names in dictionary.items(): print('{0}: {1}'.format(sport, ', '.join(names)))