딕셔너리 value 여러개 추가

케나·2022년 3월 8일
0
post-custom-banner

✅ 딕셔너리에 value에 list 추가

from collections import defaultdict
clotheslist = defaultdict(list)
clotheslist[i].append(n) # clotheslist[i] = n 필요 없음        

➰ 예시

from collections import Counter, defaultdict
def solution(clothes):
    clotheslist = defaultdict(list)
    for n,t in clothes:
        clotheslist[t].append(n)

++ ✅ defaultdict 사용없이 딕셔너리에 리스트 추가하는 방법

closet = dict() 
for name, category in clothes: 
  if category in closet: closet[category].append(name) 
  else: closet[category] = [name] ##

➰ 예시

def solution(clothes):
    clotheslist = {}
    for n,t in clothes:
        if t in clotheslist:
            clotheslist[t].append(n)
        else: 
            clotheslist[t] = [n] #####
    print(clotheslist)

✅ 딕셔너리에 int값 활용

from collections import defaultdict
clotheslist = defaultidct(int)
clotheslist[t] += 1

➰ 예시

from collections import defaultdict
def solution(clothes):
    clotheslist = defaultdict(int)
    for n,t in clothes:
        clotheslist[t] += 1

key=operator.itemgetter(1)
key값으로 sort
sorted(dic.items(), key=lambda x:x[1]) # 값으로 정렬

post-custom-banner

0개의 댓글