딕셔너리 & 집합

mong·2022년 10월 1일
1

Python Study

목록 보기
1/2
post-thumbnail

Python Set

: 딕셔너리와 굉장히 비슷하지만 다른 점이 있음

: { 중괄호 } 안에 넣어줌

myset = { "apple" , "banana", "cherry" }
print(myset)

>> {'banana', 'cherry', 'apple'}

Set의 특징

  1. unordered

    : list의 경우 ordered기 때문에 myset을 출력시키면 그대로 순서대로 출력되지만, set의 경우 unordered기 때문에 무작위로 출력된다. (위에 코드 예시)

  2. change 할 수가 없음

    : 기존의 item을 다른 것으로 수정할 수는 없지만 추가나 삭제 하는 것은 가능.

  3. duplicate(중복)이 허용되지 않음

  4. 배열처럼 indexing을 사용할 수 없음 → 사용하려면 list로 바꿔서 사용해야 함

3번 예시

myset = { "apple" , "banana", "cherry", "apple" } #apple을 중복으로 넣으면
print(myset)

>> {'banana', 'cherry', 'apple'}    # 하나를 임의로 제거시킴

print(len(myset))

>> 3  # apple이 하나가 제거돼서 3이 됨

Data Type

: 3가지(string, 숫자, boolen) 모두 가능

set1 = { "apple" , "banana", "cherry" }   # 문자열
set2 = { 1, 3, 5, 7 }                     # 숫자
set3 = { False, True }                    # boolen

set4 = { "mask", 2022, True, 10, "set" } # 혼합도 가능 # type: class set

# set도 constructor를 사용해서 만들 수 있음
myset = set(("mask", 2022, True, 10, "set"))
print(myset)

>> {True, 2022, 10, 'set', 'mask'}

Loop & Access

myset = { "apple" , "banana", "cherry" }

for i in myset:
	print(i)

>> banana
   cherry
   apple

print("banana" in myset)   # banana가 myset에 있는지 확인

>> True

Add Set Items

# add로 추가
myset.add("orange")
print(myset)

>> {'orange', 'banana', 'cherry', 'apple'}

# update로 추가
fruit = {'pineapple', 'mango'}

myset.update(fruit)
print(myset)

>> {'cherry', 'pineapple', 'apple', 'orange', 'banana', 'mango'}

# list와 다른 점: 뒤로 들어가지 않고 무작위로 들어감
# update의 경우, list와도 호환이 돼서 똑같이 들어감

fruit_list = ['pineapple', 'mango']

myset.update(fruit_list)
print(myset)

>> {'cherry', 'pineapple', 'apple', 'orange', 'banana', 'mango'}

Remove Set Items

# remove로 제거
myset.remove('banana')
print(myset)

>> {'cherry', 'pineapple', 'apple', 'orange', 'mango'}

# discard로 제거
myset.discard('mango')
print(myset)

>> {'cherry', 'pineapple', 'apple', 'orange'}

# pop으로 제거  
# set이 unordered이기 때문에 어떤 item이 remove 될지 알수 없음
a = myset.pop()
print(a)   # 어떤 item이 remove 됐는지 확인하기 위함.
print(myset)

>> cherry
>> {'pineapple', 'apple', 'orange'}

# clear  # 다 제거
myset.clear()
print(myset)

>> set()   # 아무것도 없음

# del  # myset 자체를 없앰
del myset

Join Sets

myset = { "apple" , "banana", "cherry" }
set1 = {1, 2, 3}

set2 = myset.union(set1)
print(set2)

>> {1, 2, 'cherry', 3, 'apple', 'banana'}

# 중복되는 것만 유지
a = { "apple" , "banana", "cherry" }
b = { "google", "apple", "samsung" }

a.intersection_update(b)   # 함수를 사용하여 교집합인 부분만 유지
print(a)                   # a가 new set으로 update 됨

>> {'apple'}

a = { "apple" , "banana", "cherry" }
b = { "google", "apple", "samsung" }

c = a.intersection(b)   # 함수를 사용하여 교집합인 부분만 따로 빼기
print(c)

>> {'apple'}



Python Dictionaries

: key와 value로 이루어져있음

dict1 = {
	'name': 'Ann',
	'age': 12
}

print(dict1)

>> {'name': 'Ann', 'age': 12}

# 3.7 버전에서 딕셔너리는 ordered되어 있음
# 3.6 버전 이하는 unordered
print(dict1['name'])
>> Ann

dictionary 특징

  1. tuple, set과는 다르게 change 가능
  2. duplicate는 허용되지 않음
dict1 = {
	'name': 'Ann',
	'age': 12,
	'age': 13   # age 중복
}

print(dict1)

>> {'name': 'Ann', 'age': 13}   # 13으로 덮어씌워짐

Access Dictionary Items

x = dict1.get('name')   # name value에 접근
print(x)

>> Ann

x = dict1.keys()   # key 가져오기
print(x)

>> dict_keys(['name', 'age'])

Change Dictionary Items

dict1['name'] = 'Ariel'    # name value를 Ann에서 Ariel로 직접적으로 수정
print(dict1)

>> {'name': 'Ariel', 'age': 13}

dict1.update({'name': 'Mirabel'})   # name value 값 수정(update)
print(dict1)

>> {'name': 'Mirabel', 'age': 13}

Add Dictionary Items

# 그냥 바로 추가
dict1['tall'] = 160
print(dict1)

>> {'name': 'Mirabel', 'age': 13, 'tall': 160}

# update 사용해서 추가
dict1.update({'color': 'blue'})
print(dict1)

>> {'name': 'Mirabel', 'age': 13, 'tall': 160, 'color': 'blue'}

Remove Dictionary Items

  • pop & popitem
  • del
dict1.pop('name')   # name value & key 삭제
>> 'Mirabel'

print(dict1)    # name item 삭제됨
>> {'age': 13, 'tall': 160, 'color': 'blue'}

# 가장 마지막으로 추가된 항목 삭제
dict1.popitem()   

print(dict1)
>> {'age': 13, 'tall': 160}

# del로 item 삭제
del dict1['age']

print(dict1)
>> {'tall': 160}

# del & clear로 dictionary 를 완전히 없애는 것도 가능

Loop Dictionaries

  • items: 키-값 쌍을 모두 가져옴
  • keys: 키를 모두 가져옴
  • values: 값을 모두 가져옴
# key만 출력
dict2 = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
for i in dict2:      # for i in dict2.keys(): 해도 결과 같음
	print(i, end=' ')

>> a b c d

# value만 출력
for value in dict2.values():
	print(value, end=' ')

>> 1 2 3 4

for key, value in dict2.items():
	print(key, value)

>> a 1
	 b 2
	 c 3
	 d 4

0개의 댓글