데이터를 비순차적(unordered)으로 저장할 수 있는 순열 자료구조(collection). 주로 중복된 값을 골라내야 할때, 빠른 look up을 해야 할 때, 그러면서 순서가 상관없는 데이터를 취급할때 사용된다.
x = set(['wecode', 'wework', 'wecode'])
print(x) #'wecode', 'wework'
x.add('weplay')
print(x) #'wecode', 'wework', 'weplay'
x.add('weplay') #데이터 중복
print(x) #'wecode', 'wework', 'weplay'
다른 언어에서는 hashmap, hash table이라고 불리기도 한다. Key-Value 형태의 값을 저장할 수 있는 자료구조이다. 데이터베이스처럼 키와 값을 묶어서 데이터를 표현해야 할때 유용하다.
# 데이터가 주어지거나 딕셔너리의 내용이 고정되어 있는 경우
dictionary1 = {
'name' : ['Ryan', 'Lee'],
'job' : 'sw engineer',
'address' : {
'city' : 'seoul',
'zip_code' : '1234'
}
}
# 딕셔너리 변수를 선언해놓고 데이터 베이스를 조회해서 필요한 정보를 동적으로 채워야 하는 경우
dictionary2 = {}
dictionary2['name'] = ['Ryan','Lee']
dictionary2['job'] = 'sw engineer'
dictionary2['address'] = {'city': 'seoul', 'zip_code' : '1234'}
# 문자열로만된 딕셔너리의 키로 사용할 수 있는 경우
dictionary3 = dict(
name=['ryan','lee'],
job='sw engineer',
address = {'city':'Seoul', 'zip_code' : 1234}
)
# 튜플로 받아온 정보로 키와 값을 만들어야 할 경우
dictionary4 = dict(
[('name' , ['Ryan', 'Lee']),
('job','sw engineer'),
('address', {'city':'Seoul', 'zip_code' : '1234'})]
)
해쉬(hash)
는 단방향(one-way) 암호화 기술이다. 즉, 한번 암호화 하면 복호화가 안된다. 실제 암호화되는 데이터의 길이와 상관없이 항상 일정한 길이의 해쉬값을 가지기 때문에 주로 임의의 길이의 데이터를 고정된 길이의 데이터로 매핑할때 사용된다.
import hashlib
def sha1_hash(str):
hash_obj = hashlib.sha1(str.encode())
hash_value = hash_obj.hexdigest()
return hash_value
hash_value_wecode = sha1_hash('wecode')
print(hash_value_wecode) # 283463014a3f8ab829fcf9087ff85d50da1d1bb6
print(len(hash_value_wecode)) # 40
hash_value_1234 = sha1_hash('1234')
print(hash_value_1234) # 7110eda4d09e062aa5e4a390b0a572ac0d2c0220
print(len(hash_value_1234)) # 40
데이터의 길이(6,4)는 각각 다르지만 해쉬값은 동일한 길이(40)를 가지는 것을 확인할 수 있다.