[TIL]set, dictionary

YUJIN'S CODE·2021년 10월 12일
0

python

목록 보기
3/4
post-thumbnail

파이썬에는 크게 set, dictionary, list, tuple 4가지 자료구조가 있다. 차이점에 대해 알아보자!


1.set

1-1 set 생성, 추가 , 삭제

👉 중복된 값은 저장이 안된다.

#생성
set1 = {1, 2, 3, 1}
print(set1) #{1,2,3}

set2  = set([1, 2, 3, 1])
print(set2) #{1,2,3}

#추가
my_set = {1, 2, 3}
my_set.add(4)
print(my_set) #{1,2,3,4}

#삭제
my_set = {1, 2, 3}
my_set.remove(3)
print(my_set) #{1,2}

1-2 set에 포함된 값 알아보기

👉 in 사용하여 알아보기

my_set = {1, 2, 3}

if 1 in my_set:
    print("1 is in the set")
# 1 is in the set

if 4 not in my_set:
    print("4 is not in the set")
# 4 is not in the set

1-3 Intersection & Union

👉교집합은 "&" 합집합은 "|"을 이용한다.

# Intersection(교집합)
set1 = {1, 2, 3, 4, 5, 6}
set2 = {4, 5, 6, 7, 8, 9}

print(set1 & set2)
# {4, 5, 6}

print(set1.intersection(set2))
# {4, 5, 6}

#Union(합집합)
print(set1 | set2)
# {1, 2, 3, 4, 5, 6, 7, 8, 9}
print(set1.union(set2))
# {1, 2, 3, 4, 5, 6, 7, 8, 9}

2. dictionary

2-1 dictionary 요소 읽기, 추가

#읽기 


#추가
dict = {1:"one","two":2}
dict[3]="three"
print(dict)
#{1: 'new one', 'two': 2, 3 :'three' }

2-2 dictionary 요소 수정, 삭제

#수정
my_dict = { "one": 1, 2: "two", 3 : "three" }
my_dict["four"] = 4
print(my_dict)
# {'one': 1, 2: 'two', 3: 'three', 'four': 4

#삭제
my_dict = { "one": 1, 2: "two", 3 : "three" }
del my_dict["one"]
print(my_dict)
#{2: 'two', 3: 'three'}

🔍 set 과 dictionary 차이

  • set은 key값만 있다.
  • dictionary는 {}로 표현되고, key와 value값이 있다.
💡 중복값을 가지지 않는다는 공통점이 있다!
profile
I Love Pizza, 나만의 토핑으로 한조각씩 맞춰가는 중

0개의 댓글