HackerRank Python - DefaultDict Tutorial

The defaultdict tool is a container in the collections class of Python. It's similar to the usual dictionary (dict) container, but the only difference is that a defaultdict will have a default value if that key has not been set yet. If you didn't use a defaultdict you'd have to check to see if that key exists, and if it doesn't, set it to what you want.

  1. # Enter your code here. Read input from STDIN. Print output to STDOUT
  2. from collections import defaultdict
  3. d = defaultdict(list)
  4. n, m = map(int, input().split())
  5. for i in range(n):
  6. d[input()].append(str(i + 1))
  7. for j in range(m):
  8. print(' '.join(d[input()]) or -1)

download android app