Python

[Python] Data type : 딕셔너리(Dictionary) 와 셋(Set)

2022. 8. 22. 00:21

딕셔너리(Dictionary) 와 셋(Set)


 

딕셔너리(Dictionary) 

Key:value 형태로 데이터를 묶는 데이터 타입

 시퀀스 데이터타입과는 다르게 '키 값'으로 인덱싱을 한다.

 

 


딕셔너리 생성하기

 

방법1)

직접 {key1:value1, key2:value2, key3:value3 …} 형태로 생성

menu = {'americano':1500, 'latte':2500, 'Frappuccino':4000, 'ice':500, 'juice':4500}
print(menu, type(menu))

 

 

방법2)

딕셔너리의 Constructor 이용하기 dict(key1=value1, key2=value2  …)

menu = dict(americano=1500, latte=2500, Frappuccino=4000, ice=500, juice=4500)
print(menu, type(menu))

 


딕셔너리 특징

 

· Key값이 중복되는 경우, 한 개를 제외한 나머지는 무시된다.

· 딕셔너리 안의 특정 키의 유무 in 을 사용해서 확인할 수 있다.

menu = {'americano':1500, 'latte':2500, 'Frappuccino':4000, 'ice':500, 'juice':4500}
print('Frappuccino' in menu)     # True

 

· 딕셔너리의 get() 을 사용해서도 가져올 수 있다.

   이 때, 두번째 파라미터에 값을 주어 기본값으로 지정해줄 수 있다.

menu = {'americano':1500, 'latte':2500, 'Frappuccino':4000, 'ice':500, 'juice':4500}

print(menu.get('juice'))
print(menu.get('greentea'))            # 메뉴에 없는 greentea를 키에서 호출
print(menu.get('greentea','메뉴없음'))  # 두번째 파라미터에 기본값으로 '메뉴없음' 지정


 

셋(set)

집합의 형태를 쉽게 처리하기 위한 데이터 타입

set은 키(Key) 없다!


set 생성하기

 

방법1)

직접 {value1, valu2, value3 …} 형태로 생성

set_a = {1, 2, 3}
print(set_a)
print(type(set_a))

 

방법2)

셋의 Constructor 이용하기

a = set((1,2,3))
print(a, type(a))

b = set([1,2,3])
print(b, type(b))

c = set({1,2,3})
print(c, type(c))


set 특징

· 중복을 허용하지 않는다.

menu = {'americano','americano','latte','juice','greentea'}
print(menu, type(menu))

 

· 순서가 없기 때문에 인덱싱이 불가능하다.

menu = {'americano','americano','latte','juice','greentea'}
print(menu[0])

 

· 집합의 형태를 쉽게 처리하는 데이터 타입이므로 합집합, 교집합, 차집합을 쉽게 구할 수 있다.

group1 = {1,4,6,2,4}
group2 = {2,3,4,5,7,3,2}

print(group1&group2) # 합집합
print(group1|group2) # 교집합
print(group1-group2) # 차집합