DefaultDict Tutorial

Sort by

recency

|

1116 Discussions

|

  • + 0 comments
    from collections import defaultdict
    
    n=input()
    n,m=map(int,n.split())
    d=defaultdict(list)
    for i in range(n):
        word=input()
        d[word].append(i+1)
    
    for i in range(m):
        word=input().strip()
        if word in d:
            ans=d[word]
            ans=map(str,ans)
            newans=" ".join(ans)
            print(newans)
        else:
            print(-1)
    
  • + 0 comments
    from collections import defaultdict
    if __name__ == '__main__':
        n,m = map(int, input().split())
        A = defaultdict(list)
        
        for i in range(1,n+1):
            a = input()
            A[a].append(i)
    
        for _ in range(m):
            B = input()
            if B in A:
                print(" ".join(map(str,A[B])))
            else:
                print(-1)
    
  • + 0 comments
    from collections import defaultdict
    
    d=defaultdict(list)
    
    m,n = input().split()
    
    for i in range(1,int(m)+1):
        a = input()
        d[a].append(i)
    
    for _ in range (int(n)):
        b = input()
        
        if b in d:
            print(*d[b])
        else:
            print('-1')
    
  • + 0 comments

    from collections import defaultdict

    A=defaultdict(list) n,m=list(map(int, input().split())) for i in range(1,n+m+1): word=input() if i<=n: A[word].append(i) elif word in A.keys(): print(*A[word]) else: print(-1)

  • + 1 comment

    I really don't see the point of this thing. In most cases I though about I had to check if it was empty at some point anyway or if it was present inside the list so it's just adding overhead and you still need to check. Isn't it useless in most cases ?

    Plus in normal dict you can already use: d = dict() d.get(key, default_value) `