
.get(key[,default]) person = {"name": "Alcie", "age": 25}
print(person.get("name") # Alice
print(person.get("country") # None
print(person.get("country", "Unknown") # Unknown
print(person["country"] # KeyError: "country"
.keys()person = {"name": "Alcie", "age": 25}
print(person.keys()) # dict_keys(["name", "age"])
for item in person.keys():
print(item)
"""
name
age
"""
values() person = {"name": "Alcie", "age": 25}
print(person.values()) # dict_values(["Alice", "25"])
for item in person.values():
print(item)
"""
Alice
25
"""
items() person = {"name": "Alcie", "age": 25}
print(person.values()) # dict_items([("name", "age") ("Alice", "25")])
for item in person.values():
print(item)
"""
name Alice
age 25
"""
.setdefault(key[,default]) default 와 연결한 키를 딕셔너리에 추가하고 default 를 반환한다.person = {"name": "Alcie", "age": 25}
print(person.setdefault("country", "Korea")) # Korea
print(person) # {"name": "Alice", "age": 25, "country": "Korea"}
.update([*other*])other 가 제공하는 키/값 쌍으로 딕셔너리를 갱신하고 기존 키는 덮어쓴다.person = {"name": "Alcie", "age": 25}
other_person = {"name": "Jane", "country": "Korea"}
person.update(other_person)
print(person) # {"name": "Jane", "age": 25, "country": "Korea"}
person.update(age= 100, address = "Seoul")
print(person) # {"name": "Jane", "age": 100, "country": "Korea", "address": "Seoul"}
pop(key[,default])default를 반환한다.)person = {"name": "Alcie", "age": 25}
print(person.pop("age")) # 25
print(person) # {"name": "Alice"}
print(person.pop("country", None)) # None
print(person.pop("country")) # KeyError
clear() person = {"name": "Alcie", "age": 25}
person.clear()
print(person) # {}
defaultdictdefaultdict : 파이썬 내장 모듈 collections에서 제공하는 딕셔너리의 확장판이다.딕셔너리에 존재하지 않는 키를 조회할때, 자동으로 “기본값”을 생성해주는 자료구조이다.
KeyError 걱정 없이 값을 수정하거나 추가할 때 매우 유용하다.
text = "banana"
counts = {}
for char in text:
if char not in counts: # 키가 있는지 매번 확인
counts[char] = 0
counts[char] += 1
print(counts) # {"b":1, "a": 3, "n": 2}
from collections import defaultdict
text = "banana"
counts = defaultdict(int) # 기본값을 정수(0)으로 설정
for char in text:
# 키 확인 불필요! 없으면 0으로 자동 생성 후 +1
counts[char] += 1
print(counts) # defaultdict(<class "int">, {"b": 1, "a": 3, "n": 2})
defaultdict(int) → 키가 없으면 0으로 초기화defaultdict(list) → 키가 없으면 빈 리스트 [] 로 초기화고유한 항목들의 정렬되지 않은 컬렉션이다.
- Set은 내부적으로 해시 테이블을 사용하여 데이터를 저장한다.
- 항목의 고유성을 효율적으로 보장하고, 항목의 추가, 삭제, 존재 여부 확인이 데이터의 크기에 관계 없이 매우 빠르다.
- 수학적인 잡합 연산을 간편하게 수행할 수 있는 것이 가장 큰 특징이다.
.add(x) : 세트에 x를 추가한다.my_set = {"a", "b", "c", 1, 2, 3}
my_set.add("d")
print(my_set) # {1, "b", 3, 2, "c", "d", "a"}
my_set.add("d")
# 순서가 없지만 같은 프로그램을 실행하는 동안은 같은 순서
print(my_set) # {1, "b", 3, 2, "c", "d", "a"}
.remove(x) : 항목에서 x를 제거한다. x가 없을 경우 keyError가 발생한다.my_set = {"a", "b", "c", 1, 2, 3}
my_set.remove(2)
print(my_set) # {"b", 1, 3, "c", "a"}
my_set.remove(10) # KeyError: 10

해시 테이블은
키, 값을 저장하는 자료구조이다.

임의의 크기를 가진 데이터를 고정된 크기의 고유한 값으로 변환하는 것 이다.
순서 보다는 버킷 위치 (인덱스) 가 요소의 위치를 결정한다.순서를 보장하지 않는다!!!난수를 생성할 때 사용하는 시작값
- 계산 순서
- 시드(seed)를 설정한다.
- 시드를 기준으로 난수 생성 알고리즘이 실행된다.
- 난수가 생성된다.
- 같은 시드 → 같은 난수, 다른 시드 → 다른 난수
예시
random.seed(10)
10(시드)
↓
난수 생성 알고리즘
↓
5 → 2 → 6 → 1 ...
프로그램 실행마다 해시 계산에 사용할 시드를 바꿔 보안을 강화하는 기능
- 계산 순서
- 프로그램이 시작된다.
- 파이썬이 랜덤한 Hash Seed를 생성한다.
- Hash Seed를 이용해
hash()값을 계산한다.- 계산된 해시값으로
dict,set의 저장 위치를 결정한다.- 프로그램을 다시 실행하면 Hash Seed가 바뀌어 저장 위치도 달라질 수 있다.
예시
프로그램 시작
↓
Hash Seed 생성 (1234)
↓
hash("apple") 계산
↓
저장 위치 결정
다시 실행
프로그램 시작
↓
Hash Seed 생성 (9876)
↓
hash("apple") 계산 (이전과 다른 값)
↓
저장 위치 변경
int, str , tuple (단, 내부에 불변만 있을 경우에만)list, dict , set )은 기본적으로 해시 불가능하다.