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)




codesadda.com

Codesadda.com is your home of programming solutions, tutorials, video tutorials and much more. Sign Up for our weekly newsletter to get update about new content.

Like us on Facebook | Connect with us on LinkedIn | Subscribe our Channel on Youtube