DefaultDict Tutorial : HackerRank Solution in Python

Shounak Lohokare
2 min readJan 12, 2021

Solution in Python 3

Link:- DefaultDict (github.com)

from collections import defaultdict
n, m = map(int, input().split())
d = defaultdict(list)for i in range(n):
d[input()].append(i+1)
for j in range(m):
s = input()
if s in d:
print(*d[s])
else:
print(-1)

Explanation

First we will import defaultdict from collections module of Python. Then we will accept n and m from the input stream.

n, m = map(int, input().split())

The above map function applies the int to the items of input().split() and stores the respective values in variables n and m.

Subsequently, we declare a defaultdict and pass a list as its parameter which will make all the values of the defaultdict to be stored in the form of a Python list.

d = defaultdict(list)

Now we will use a for loop to iterate over the range of n through variable i

for i in range(n):

In the for loop we will, we will append i+1 to the defaultdict d with input() as a key

for i in range(n):
d[input()].append(i+1)

i+1 represents the positions of words in group A which are accepted from the input stream. We append i+1 because in the Python’s range function starts iteration from 0.

Thus in the above for loop we store index positions of words that occur in word group A.

Then we will declare another for loop to iterate over range of m, through a variable j.

for j in range(m):

In the for loop we will accept the word whose positions are to be outputted in a variable called s.

s= input()

Then we will check if s exists as a key in the default dictionary d,

if s in d:

If s exists as a key in d, then the index occurrences of the word exists in group A and thus we print the values of the word in the defaultdict d.

for j in range(m):
s = input()

if s in d:
print(*d[s])

The * in the print functions enables us to print the value(s) of a list in form of a string, that is, without commas and square brackets.

If s doesn’t exist as a key then we print -1.

else:
print(-1)

Thus the second for loop accepts the words belonging to word group B and checks whether the word has appeared in group A, if it has displays the indices of each occurrences else it prints -1.

--

--

Shounak Lohokare

pretending to teach is one of the best way to learn.