Python Basics - Set & Dictionary

Jayson Hwang·2022년 4월 27일
0

09. set(집합)

<<<set>>>
  myset = {"apple", "banana", "cherry"}

중복 안됨, 순서 없음

  • 여러 개의 데이터를 집합의 형태로 넣을 수 있음
  • set 자료형의 핵심은 요소들의 중복을 허용하지 않음
  • 데이터 간 순서가 없기때문에 리스트나 튜플처럼 인덱싱이나 슬라이싱을 이용하여 값을 추출해내는 방법을 사용할 수 없음

A set is a collection which is unordered, unchangeable, and unindexed.

  • Unordered:
    The items in a set do not have a defined order.
    Set items can appear in a different order every time you use them, and cannot be referred to by index or key.
  • Unchangeable:
    Once a set is created, you cannot change its items, but you can remove items and add new items.
  • Duplicates Not Allowed:
    Sets cannot have two items with the same value.
    thisset = {"apple", "banana", "cherry", "apple", "cherry"}
    print(thisset) # {'cherry', 'banana', 'apple'}


📌 09-1. set의 선언방법

1. my_set = {1, 2, 3}
2. my_set = set([1, 2])


📌 09-2. set의 연산

java = {"유재석", "김태호", "양세형"}
python = set(["유재석", "박명수"])

▶︎ 교집합
    print(java & pyhton)
    print(java.intersection(python))
    # {"유재석"}

▶︎ 합집합
    print(java | python)
    print(java.union(python))
    # {"김태호", "박명수", "유재석", "양세형"}

▶︎ 차집합
    print(java - python)
    print(java.difference(python))
    # {"김태호", "양세형"}

▶︎ 세트에 하나의 값 추가
    python.add("김태호")
    print(python)
    # {"박명수", "김태호", "유재석"}
    
▶︎ 세트에 여러 값 추가
	python.update(["김태호", "하하", "노홍철"])
    print(python)
    # {'박명수', '노홍철', '유재석', '김태호', '하하'}
    # **update()함수 괄호 안에 [ ]을 사용해서 값을 묶어줘야함**

▶︎ 세트에서 값 제거
	java.remove("김태호")
    print(java)
    # {"양세형", "유재석"}


🚀 자료 구조의 변경

LIST -> [ ]
SET -> { }
TUPLE -> ( )

  menu = {"coffee", "milk", "juice"}
  print(menu, type(menu))
  #{'milk', 'coffee', 'juice'} <class 'set'>

  menu = list(menu)
  print(menu, type(menu))
  #['milk', 'coffee', 'juice'] <class 'list'>

  menu = tuple(menu)
  print(menu, type(menu))
  #('milk', 'coffee', 'juice') <class 'tuple'>

  menu = set(menu)
  print(menu, type(menu))
  #{'milk', 'coffee', 'juice'} <class 'set'>



10. Dictionary

thisdict = {
	"brand": "Ford",
    "model": "Mustang",
    "year": 1964
}


📌 10-1. dictionary란?

  • 데이터를 key와 value가 대응되는 형태로 하나의 변수에 선언하는 자료형
  • 순차적인 index값을 요구하지 않고, key값을 통해 value를 얻음
  • 중괄호{ }를 사용하여 {key:value} 형태로 선언
    ex) {key1:value1, key2:value2, key3:value3}
  • key에는 변하지 않는 값을 써주며 중복이 불가하다.
  • 반면 value에는 변하는 값과 변하지 않는 값 모두 사용 가능


🚀 Set 과 Dictionary 차이점?

  • Set은 Key값만 / Dictionary는 Key와 Value 값
profile
"Your goals, Minus your doubts, Equal your reality"

0개의 댓글