프리렉 - FREELEC
http://freelec.co.kr/book/catalogue_view.asp?UID=134
이강성저
menu = {'odeng':300, 'sundae':400, 'mandu':500}
menuselection = 'sundae'
menu[menuselection]
menuselection = 'mandu'
menu.get(menuselection, 0)
menuselection = 'steak'
menu.get(menuselection, 0)
사전의 키는 해쉬 가능해야(hashable) 한다. 해쉬 가능하다는 뜻은 객체를 해쉬 메모리 공간에 매핑 시킬 수 있다는 뜻이다. 만일 객체가 변경 가능하다면 (mutable), 그 객체는 해쉬 공간 매핑 주소가 변경될 것이므로 변경 가능한 객체는 기본적으로 해쉬가능하지 않은 것으로 취급한다. 따라서, 변경가능하지 않은 (immutable) 객체이면서 해쉬 가능한 객체들이 사전의 키로 사용될 수 있다. 수치자료형, 문자열, 바이트, 튜플 등은 사전의 키로 사용 가능하며, 리스트, 사전등은 키로 사용가능하지 않다.
L1 = [1,2,3]
L2 = [4,5,6]
d = {'low':L1, 'high':L2}
e = d
f = d.copy()
d['low'] = [10, 20, 30]
d['high'][1] = 500
e
f # d를 복사했음에도 불구하고 d의 변경이 f에 영향을 미치는 점에 유의
d = {'one':1, 'two':2, 'three':3, 'four':4, 'five':5}
sorted(d.items())
sorted(d.items(), key=lambda a:a[1])
keys = ['one', 'two', 'three', 'four']
values = [1, 2, 3, 4]
dict(zip(keys, values))
s = 'one two one two three four'
d = {}
for w in s.split():
d[w] = None
list(d.keys())
# 집합을 이용하면 간단히 해결된다
list(set(s.split()))
s = 'We propose to start by making it possible to teach programming in Python, an existing scripting language, and to focus on creating a new development environment and teaching materials for it.'
import re
s2 = re.sub('[,.]', '', s.lower())
s2
ws = s2.split()
import collections
collections.Counter(ws)
sorted(list(collections.Counter(ws).items()))
tab = {'a':'w', 'b':'x', 'c':'y', 'd':'z', 'w':'a', 'x':'b', 'y':'c', 'z':'d'}
s = 'abcd wxyz'
s2 = ''
for c in s:
s2 += tab.get(c, c)
s2