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)
Please click on the like button if it worked

Solution not working or have any suggestions? Please send an email to [email protected]

donate a cup of tea :)

Join Our Facebook Group

Share this solution


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