Python has a very useful set of data structures in one of its modules called
collections. One of those data structures is a dictionary with a default value -
When creating a
defaultdict, we can pass a lambda function that would return a default value for missing elements:
d = defaultdict(lambda: 'This item does not exist') d['Anna'] = 10 d['Bob'] = 9 print(d['Bob']) # 9 print(d) # This item does not exist
Bobare added to the keys of the dictionary but
999is not present, so the program prints
This item does not exist.
This is especially useful when dealing with lists as values:
grades = defaultdict(lambda: ) grades['Anna'].append(10) grades['Anna'].append(9) grades['Bob'].append(8) grades['Bob'].append(9) print(grades['Bob']) # [8, 9] print(grades) # 
nmatches of football teams and their opponents, you are asked to find out the number of matches each team played.
The first line of the input contains a single integer
n- the number of matches. The next
nlines contain dash (
-) separated team names that played against each other. The following line contains comma-separated (
,) names of the clubs for which the program should print the number of matches played.
The program should print space-separated numbers of matches for each of the teams requested on the last line of the input.
3 Real Madrid-Barcelona Chelsea-Manchester United Arsenal-Barcelona Manchester United,Barcelona,Roma
1 2 0