Prepare > Python > Collections > DefaultDict Tutorial

2023. 8. 16. 21:07HackerRank-Python

 

DefaultDict Tutorial | HackerRank

Create dictionary value fields with predefined data types.

www.hackerrank.com

 

문제


Input Format

The first line contains integers, n and m separated by a space.
The next n lines contains the words belonging to group A.
The next m lines contains the words belonging to group B.

Output Format

Output m lines.
The  line should contain the -indexed positions of the occurrences of the  word separated by spaces.

 

=> 그룹 B에 있는 m개의 단어들이 그룹 A에 있으면 그룹 A에서의 단어가 있는 인덱스들을, 없으면 -1 을 출력하라

 

 

 

 

코드


from collections import defaultdict


n, m = tuple(map(int, input().split()))
N = defaultdict(list)


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


for j in range(m):
    k = input()
    
    if k in N.keys():
        print(' '.join(N[k]))
    else:
        print(-1)

 

 

 

 

노트


defaultdict()

from collections import defaultdict
d = defaultdict(list)
d['python'].append("awesome")
d['something-else'].append("not relevant")
d['python'].append("language")
for i in d.items():
    print(i)
    
#('python', ['awesome', 'language'])
#('something-else', ['not relevant'])

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.

 

=> defaultdict 에 대한 설명

dictionary의 하위 클래스임dict는 key값이 없으면 오류지만 defualtdict는 아님(이거 뭔소린지 모르겠네. 참조링크로 보자)

 

 

활용 예시

s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
d = defaultdict(list)
for k, v in s:
    d[k].append(v)

print(sorted(d.items()))

# [('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]
s = 'mississippi'
d = defaultdict(int)
for k in s:
    d[k] += 1

print(sorted(d.items()))

# [('i', 4), ('m', 1), ('p', 2), ('s', 4)]

 

 

' '.join()의 입력 자료형

from collections import defaultdict


n, m = tuple(map(int, input().split()))
N = defaultdict(list)


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


for j in range(m):
    k = input()
    
    if k in N.keys():
        print(' '.join(N[k]))
    else:
        print(-1)

로 하면 오류 발생.

  • 실험과 구글링 대충 해본 결과, join()은 숫자형 자료를 거부하는것을 깨닳음..

 

 

 

두 번째 시도

from collections import defaultdict 
d= defaultdict(list)

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

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

for j in range(m):
    B = input()
    if B in d.keys():
        print(' '.join(d[B]))
    else:
        print(-1)
  • 같은 풀이

 

 

 

 

참조


 

[파이썬 자료구조] defaultdict dictionary 차이와 활용

1. defaultdict 소개 dict 클래스의 서브 클래스 dictionary에서는 (key,value)로 사용된다. 기존 dictionary에서 접근할 때 key의 값이 없거나 없는 key를 조작할려할 때 keyError가 발생한다. 이를 보완한 것이 defa

siloam72761.tistory.com

 

4.4 딕셔너리(dict)

오늘 제가 여러분과 함께 공부할 것은 딕셔너리 자료형이예요. 사전을 한번도 못 보신 분은 안 계시죠? **dictionary** n. pl. dictionaries 1. …

wikidocs.net

 

 

collections — Container datatypes

Source code: Lib/collections/__init__.py This module implements specialized container datatypes providing alternatives to Python’s general purpose built-in containers, dict, list, set, and tuple.,,...

docs.python.org