python

[python] 셋 | 딕셔너리

전감자(◔◡◔) 2022. 9. 22. 22:22
'''
집합형 set
4. set
-표현 :{값1,값2,...} set(iterable)

- 타입 type([10,20]) ==> <class 'list'>
                    ==> 셋은 클래스로 만들어짐
-특징: 순서 없고 중복 불가,
저장되는 값은 immutable 해야한다. 따라서 리스트는 저장 불가

#. 집합 연산 함수 제공 (교집합, 합집합, 차집합)
-intersection(교집합)
-difference(차집합)
-union(합집합)


-함수 정리
print(dir(set))
'''

print(dir(set))

'''

'__and__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__',
 '__getattribute__', '__gt__', '__hash__', '__iand__', '__init__', '__init_subclass__', '__ior__', '__isub__', 
 '__iter__', '__ixor__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__or__', '__rand__', '__reduce__', 
 '__reduce_ex__', '__repr__', '__ror__', '__rsub__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', 
 '__subclasshook__', '__xor__', 
 
 
 'add', 'clear', 'copy', 'difference', 'difference_update', 'discard', 'intersection', 'intersection_update',
 'isdisjoint', 'issubset', 'issuperset', 'pop', 'remove', 'symmetric_difference', 'symmetric_difference_update', 
 'union', 'update'

'''

# 1. 셋 생성
m = {1,2,3,3,3,5,5}
m2 = set("hello")
m3 = set("helloHellO")
m4 = set([1,2,22,3,3,4,5,5])

print(m,m2,m3,m4)

#immutable한 데이터만 저장됨.mutable한 리스트 저장불가
#m5= {[1, 3], [2]}
#print(m5)


#2. 함수
#가. add(element) : 값 추가
m={1,2}

help(m.add)
m.add(10)
m.add(3.15)
m.add(3.15)
m.add("hello")
m.add((10,3))
print(m)
#나 .update :값 병합 (집합형 vs 집합형)

m={1,2}

#일반형 불가 m.update(10)
m.update({3,4,5})
m.update((30,40,50))
m.update("hello")
m.update([300,400,500])#리스트 가능
print(m)

#다. 삭제

m={1,2,3,4,5}
m.pop() # 임의의 값 삭제
print(m)
m.remove(3)# 값으로 삭제, 값이 일치하지 않으면 keyError 발생
print(m)
m.discard(5) # 값으로 삭제, 일치하지 않으면 do nothing
print(m)
m.clear()
print("셋 길이:",len(m))

#교집합/합집합/차집합
n={1,2,3,4}
n2={5,2,3,6,7}

print("합집합",n.union(n2))
print("교집합",n.intersection(n2))
print("차집합",n.difference(n2))
print("차집합",n2.difference(n))
print("대칭 차집합",n.symmetric_difference(n2))

'''

4. 딕셔너리(dictionary)
-표현 :{key:value,name:value}
    dict(key=value,key=value) ***** 중요
    dict(중첩리스트)==> dict([['a','b'],['c','d']])

- 타입 type({key:value,key:value}) ==> <class 'dict'>
                    ==> 딕셔너리는 클래스로 만들어짐
-특징: 다른 집합형(문자열,리스트,튜플,셋)은 값만 지정해서 사용함,
    딕셔너리는 key:value 형식으로 지정해서 사용함
    (key 값만 알면 value값을 바로 조회 가능하다. 검색속도가 매우 빠르다)
    key를 이용해서 value값을 관리한다.(조회, 삭제, 수정)

-함수 정리
'''

#print(dir(dict))

'''
'__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', 
'__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', 
'__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__setattr__', 
'__setitem__', '__sizeof__', '__str__', '__subclasshook__', 


'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values'

'''

#1. dict 생성
m={'name':"홍길동","age":20}
m2=dict(name="홍길동",age=20)
m3=dict([['name',"홍길동"],["age",20]])

print(m,m2,m3)

#2. 조회1==>m["key"] (*)
m={'name':"홍길동","age":20}
print(m["name"],m["age"],)
#print(m["address"]) 존재하지 않는 key 지정시 KeyError

#2. 조회2 ==> m.get("key"), key값을 주면 value를 return
m={'name':"홍길동","age":20}
print(m.get("name"),m.get("age"))
print(m.get("address")) # 존재하지 않는 key 지정시 None 반환
print(m.get("address","서울")) # 존재하지 않는 key 지정시 None 대신 기본값 설정 가능


#3. 조회3==>
m={'name':"홍길동","age":20,"address":"서울"}
keys=m.keys()
print(keys) #dict_keys(['name', 'age', 'address'])
print(list(keys)) #['name', 'age', 'address']

#반복문으로 key,value값 조회
for key in list(keys):
    print(key,m.get(key),m[key])

#2. 조회4 ==> value만 얻기, m.values()
m={'name':"홍길동","age":20,"address":"서울"}
values=m.values()
print(values) #dict_values(['홍길동', 20, '서울'])
print(list(values))

for v in list(values):
    print(v)

#2. 조회5 ==> key,value 얻기, m.items()
m={'name':"홍길동","age":20,"address":"서울"}
items=m.items()
print(items) #dict_items([('name', '홍길동'), ('age', 20), ('address', '서울')])
print(list(items))#[('name', '홍길동'), ('age', 20), ('address', '서울')]

for x in list(items):
    print(x)

for x,y in list(items):#items 사용시 일반적인 코드 패턴
    print(x,y)

#3. 추가
m={'name':"홍길동","age":20}
m["address"]="서울"
print(m) #새로운 key value 값이 생성되었음

#4. 수정1 m[존재하는 key]=값
m={'name':"홍길동","age":20}
m["age"]=30
print(m)

# 추가와 수정 차이는 key 값의 존재 여부이다.
# 존재하면 수정 , 존재하지 않으면 추가

#4. 수정2 - update() : 병합 기능
m={'name':"홍길동","age":20}
m.update({"address":"서울"})
print(m) #존재하지 않는 key값 :추가와 같음

#4. 수정2 - update() : 병합 기능
m={'name':"홍길동","age":20}
m.update(name="이순신",age=40)
print(m) #존재하는 key값 : 수정과 같음


#D.update([E, ]**F) -> None.  Update D from dict/iterable E and F.
#m.update({key:value, key:value}) # E
#m.update(key=value, key=value) # F

# 5 삭제
m={'name':"홍길동","age":20}
m.pop("age")
m.clear() #{}, 비어있는 중괄호는 dict 이다.

'''

    1. zip 함수
    - builtins 객체에서 제공하는 함수
    -서로 분리된 리스트를 하나로 묶어준다.

    2. dict 출력을 가독성 있게 출력

'''
#zip()
x=['서울','워싱턴','방콕']
y=[1000,2288,300]
#[('a',10),('b',20),("c",30)]
result=dict(zip(x,y))# 앞에 있는게 key가 된다.
print(result)
result=dict(zip(y,x))
print(result)

#dict 함수 가독성
from pprint import pprint as p
m = {"a":300,"b":[3400,2234,456,666],"c":{"c1":[4565],"c2":[5434234]},"d":{"d1":[4565],"d2":[5434234]},"e":{"e1":[4565],"e2":[5434234]}}
print(m)
p(m)