9 딕셔너리와 세트

2023. 10. 24. 22:45프로그래밍 공부/Python

9.1 파이썬에서의 딕셔너리 유형

9.1.1 딕셔너리란?

딕셔너리(dictionary): 중괄호로 표시되는 가변 길이의 가변적이고 연관적인 데이터 구조

 

예시)

daily_temps = {'sun': 68.8, 'mon': 70.2, 'tue': 67.2, 'wed': 71.8, 'thur': 73.2, 'fri': 75.6, 'sat': 74.0}

 

 

딕셔너리를 동적으로 조작하기 위한 몇 가지 작업

Operation Result
dict() Creates a new, empty dictionary
dict(s) Creates a new dictionary with key values and their associated values from sequence s, for example,
fruit_prices = dict(fruit_data)
where fruit_data is (possibly read from a file):
[['apples',  .66], ..., ['bananas', .49]]
len(d) Length (num of key/value pairs) of dictionary d.
d[key] = value Sets the associated value for key to value, used to either add a new key/value pair, or replace the value of an existing key/value pair.
del d[key] Remove key and associated value from dictionary d.
key in d True if key value key exists in dictionary d, otherwise returns False.

 

9.2 세트 데이터 유형

9.2.1 파이썬에서의 세트 데이터 유형

집합(set): 일반적인 집합 연산을 제공하는 중복되지 않는 순서 없는 값을 가진 가변 데이터 구조동결 집합(frozenset): 불변 집합 유형

 

세트 연산자

Set Operator Set A = {1, 2, 3}       Set B = {3, 4, 5, 6}
membership 1 in A True True if 1 is a member of set
add A.add(4) {1, 2, 3, 4} Adds new member to set
remove A.remove(2) {1, 3} Removes member from set
union A | B {1, 2, 3, 4, 5, 6} Set of elements in either set A or set B
intersection A & B {3} Set of elements in both set A and set B
difference A - B {1, 2} Set of elements in set A, but not set B
symmetric difference A ^ B {1, 2, 4, 5, 6} Set of elements in set A or set B, but not both
size len(A) 3 Number of elements in set
(general sequence operation)

예시)>>> fruit = {'apple', 'banana', 'pear', 'peach'}
>>> fruit
{'pear', 'banana', 'peach', 'apple'}
>>> 'apple' in fruit
True
>>> fruit.add('pineapple')
>>> fruit
{'pineapple', 'pear', 'banana', 'peach', 'apple'}

 

set 생성자의 이용

>>> set1 = set()          >>> vegs = ['peas', 'corn']       >>> vowels = 'aeiou'
>>> len(set1)               >>> set(vegs)                            >>> set(vowels)
0                                   {'corn', 'peas'}                           {'a', 'i', 'e', 'u', 'o'}

 

frozenset의 이용

>>> apple_colors = frozenset(['red', 'yellow', 'green'])

 

'프로그래밍 공부 > Python' 카테고리의 다른 글

11 재귀  (0) 2023.10.27
10 객체 지향 프로그래밍  (0) 2023.10.24
8 텍스트 파일  (0) 2023.10.24
7 모듈러 디자인  (1) 2023.10.23
6 객체와 사용  (0) 2023.10.23