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 - defaultdict.
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[999]) # This item does not exist
Here Anna and Bob are added to the keys of the dictionary but 999 is not present, so the program prints This item does not exist.
This is especially useful when dealing with lists as values:
Given n matches 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 n lines 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.
Input
Output
3
Real Madrid-Barcelona
Chelsea-Manchester United
Arsenal-Barcelona
Manchester United,Barcelona,Roma