티스토리 뷰
- 특성
- Key - Value 쌍의 구조를 가진 컨테이너이다.
- 다른 프로그래밍 언어에서는 연관 배열(associative array)이나 해쉬테이블(hashtable)로 불린다.
- 매우 자주 사용한다.
- 순서가 고정되어 있다고 가정하면 안된다.
- 예제
- 컨테이너
# dict의 생성 #1
d = dict()
print(type(d))
결과)
<class 'dict'>
# dict의 생성 #2
d = {}
print(type(d))
결과)
<class 'dict'>
# dictd의 생성 #3
dict = {}
dict['apple'] = 1
dict['lemon'] = 2
dict['peach'] = 3
print(dict)
결과)
{'apple': 1, 'lemon': 2, 'peach': 3}
# dictd의 생성 #4
d = dict(a = 'a', b = 'b')
print(d['a'])
결과)
a
# dict는 고정된 순서를 보장하지 않는다. (실행할 때마다 순서는 바뀐다.)
chars = {'name':'mike', 'age': '24', 'address':'san diego'}
print(chars)
결과)
{'age': '24', 'name': 'mike', 'address': 'san diego'}
chars = {'name':'mike', 'age': '24', 'address':'san diego'}
print(chars)
결과)
{'name': 'mike', 'age': '24', 'address': 'san diego'}
# dict() 함수를 이용해서 생성할 때는 key = 형식으로 인자를 준다.
chars = dict(name = 'mike', age = '24', address = 'san diego')
print(chars)
결과)
{'age': '24', 'name': 'mike', 'address': 'san diego'}
# 변수명으로 다른 사전 요소 추가
d = dict( three = 3, four = 4)
dx = dict( one = 1, two = 2, **d )
print( dx )
결과)
{'three': 3, 'one': 1, 'four': 4, 'two': 2}
- 요소 접근
# dict에서는 인덱스로 요소를 참조할 수 없다.
chars = dict(name = 'mike', age = '24', address = 'san diego')
print(chars[0])
결과)
KeyError: 0
# in 내장 키워드로 Key가 존재하는지 확인하기
chars = dict(name = 'mike', age = '24', address = 'san diego')
if 'name' in chars:
print(chars['name'])
결과)
mike
# 순회해서 Key 가져오고, Key를 통해 Value 가져오기
chars = dict(name = 'mike', age = '24', address = 'san diego')
for key in chars:
print('key: ' + key, '| value: ' + chars[key])
결과)
key: address | value: san diego
key: name | value: mike
key: age | value: 24
# items() 메쏘드를 이용해 순회하기
chars = dict(name = 'mike', age = '24', address = 'san diego')
for key, value in chars.items():
print('key: ' + key, '| value: ' + value)
결과)
key: name | value: mike
key: address | value: san diego
key: age | value: 24
# 또 다른 value 읽기 메쏘드 (키를 찾지 못해도 exception을 발생시키지 않는다.)
d = dict(one = 1, two = 2)
print(d.get('one', 'default'))
결과)
1
d = dict(two = 2)
print(d.get('one', 'default'))
결과)
default
# dict 요소의 삭제
d = dict( one = 1, two = 2 )
del d['one']
print(d)
d.pop('two')
print(d)
결과)
{'two': 2}
{}
- 언팩킹 된 사전을 다시 사전으로 묶기
# Key, Value를 가지고 사전으로 묶기
chars = dict(name = 'mike', age = '24', address = 'san diego')
key = chars.keys()
value = chars.values()
chars_dupe = zip(key, value)
print(dict(chars_dupe))
결과)
{'address': 'san diego', 'name': 'mike', 'age': '24'}
- 사전 업데이트 하기
# 항목에 assign을 하는 경우 혼동을 방지하기 위해 update() 메쏘드를 제공하는 것으로 보임
d = {
'name': 'mike',
'age': 33,
'address': 'LA'
}
d.update({'name': 'mike', 'age': 33})
print(d)
결과)
{'name': 'mike', 'address': 'LA', 'age': 33}
d.update({'name': 'mike', 'age': 34, 'address': 'LA'})
print(d)
결과)
{'address': 'LA', 'age': 34, 'name': 'mike'}
- Dict 컴프리헨션
# dict도 리스트 컴프리헨션과 같은 방식으로 사용할 수 있다.d = {
'apple': 1,
'banana': 2,
'lemon': 3
}new_d = {fruitName: value + 1 for fruitName, value in d.items()}
print('Dict value plus one: ', d, '->', new_d)
new_d2 = {fruitName: value for fruitName, value in d.items() if value > 2}
print('Dict value greater than 2: ', new_d2)
new_d3 = {fruitName: value for fruitName, value in d.items() if fruitName.startswith('a')}
print("Dict Key starts 'a':", new_d3)
결과)
Dict value plus one: {'apple': 1, 'banana': 2, 'lemon': 3} -> {'apple': 2, 'banana': 3, 'lemon': 4}
Dict value greater than 2: {'lemon': 3}Dict Key starts 'a': {'apple': 1}
# dict 컴프리헨션의 필터링
ds = {
'apple': 5,
'banana': 2,
'lemon': 3
}
rd = {k:v for k, v in ds.items() if k.startswith('a') if v > 4}
print(rd)
결과)
{'apple': 5}
- 사전과 함수 인자를 이용한 트릭
def display(name, address):
print('My name is', name + '.')
print('I live in', address + '.')
d = {
'name': 'mike',
'address': 'LA'
}
print(display(**d))
결과)
My name is mike.
I live in LA.
- 소팅된 사전 얻기
# 내장함수 sorted()를 이용해 key로 소팅된 사전을 얻을 수 있다.
d = dict(one=1, two=2)
for k in sorted(d.keys()):
print(k, d[k])
결과)
one 1
two 2
# value로 소팅된 사전 얻기
d = dict(one=2, two=1)
for k in sorted(d, key=lambda x: d[x]):
print(k, d[k])
결과)
two 1
one 2
# dict.__missing__ 서브 클래싱
from collections import Iterable
class range_dict(dict):
def __missing__(self, key):
for k, v in self.items():
if isinstance(k, Iterable):
left, right = k
if left <= key < right:
return v
raise KeyError("cannot find {} in range_dict".format(key))
codes = range_dict({
(0, 10): 'red',
(10, 100): 'yellow',
(100, 1000): 'green'
})
print(codes[99])
# 결과
yellow
# dict.__missing__ 을 이용한 passthru
class passthrudict(dict):
def __missing__(self, key):
return key
censor = passthrudict({
'hell': 'h***',
'darn': 'd*rn'
})
sentence = "That darn cat!"
print(' '.join(censor[w] for w in sentence.split()))
# 결과
That d*rn cat!
# dict를 이용한 count
ls = list(range(100))
def concordance(list):
freq = {}
for l in list:
if l not in freq:
freq[l] = 0
freq[l] += 1
return freq
print(concordance(ls))
# 결과
{0: 1, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1, 7: 1, 8: 1, 9: 1, 10: 1, 11: 1, 12: 1, 13: 1, 14: 1, 15: 1, 16: 1, 17: 1, 18: 1, 19: 1, 20: 1, 21: 1, 22: 1, 23: 1, 24: 1, 25: 1, 26: 1, 27: 1, 28: 1, 29: 1, 30: 1, 31: 1, 32: 1, 33: 1, 34: 1, 35: 1, 36: 1, 37: 1, 38: 1, 39: 1, 40: 1, 41: 1, 42: 1, 43: 1, 44: 1, 45: 1, 46: 1, 47: 1, 48: 1, 49: 1, 50: 1, 51: 1, 52: 1, 53: 1, 54: 1, 55: 1, 56: 1, 57: 1, 58: 1, 59: 1, 60: 1, 61: 1, 62: 1, 63: 1, 64: 1, 65: 1, 66: 1, 67: 1, 68: 1, 69: 1, 70: 1, 71: 1, 72: 1, 73: 1, 74: 1, 75: 1, 76: 1, 77: 1, 78: 1, 79: 1, 80: 1, 81: 1, 82: 1, 83: 1, 84: 1, 85: 1, 86: 1, 87: 1, 88: 1, 89: 1, 90: 1, 91: 1, 92: 1, 93: 1, 94: 1, 95: 1, 96: 1, 97: 1, 98: 1, 99: 1}
# collections - Counter
from collections import Counter
ls = list(range(100))
print(Counter(ls))
# 결과
Counter({0: 1, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1, 7: 1, 8: 1, 9: 1, 10: 1, 11: 1, 12: 1, 13: 1, 14: 1, 15: 1, 16: 1, 17: 1, 18: 1, 19: 1, 20: 1, 21: 1, 22: 1, 23: 1, 24: 1, 25: 1, 26: 1, 27: 1, 28: 1, 29: 1, 30: 1, 31: 1, 32: 1, 33: 1, 34: 1, 35: 1, 36: 1, 37: 1, 38: 1, 39: 1, 40: 1, 41: 1, 42: 1, 43: 1, 44: 1, 45: 1, 46: 1, 47: 1, 48: 1, 49: 1, 50: 1, 51: 1, 52: 1, 53: 1, 54: 1, 55: 1, 56: 1, 57: 1, 58: 1, 59: 1, 60: 1, 61: 1, 62: 1, 63: 1, 64: 1, 65: 1, 66: 1, 67: 1, 68: 1, 69: 1, 70: 1, 71: 1, 72: 1, 73: 1, 74: 1, 75: 1, 76: 1, 77: 1, 78: 1, 79: 1, 80: 1, 81: 1, 82: 1, 83: 1, 84: 1, 85: 1, 86: 1, 87: 1, 88: 1, 89: 1, 90: 1, 91: 1, 92: 1, 93: 1, 94: 1, 95: 1, 96: 1, 97: 1, 98: 1, 99: 1})
- Total
- 410,766
- Today
- 35
- Yesterday
- 44
- 검은왕자
- www.skilledtesting.com Erkan..
- The Braidy Tester
- Hans Schaefer's home page
- systematic-testing.com
- Software Test & Performance..
- Professional Tester Magazine
- Pairwise Testing
- Methods & Tools - Providing..
- Model-Based Testing Home Page
- Dr. Dobb's Portal
- Jeff Offutt (Professor of So..
- Jeff Tian, Ph.D., P.E., Asso..
- Specialist Group in Software..
- StickyMinds.com
- Software QA/Test Resource Ce..
- AMERICAN SOCIETY FOR QUALITY
- Software Testing and Quality..
- Association for Software Tes..
- 다음 일본어 번역
- 네이버 일본어 번역
- 고재팬 일본어 번역
- The Software Engineering Res..
- QA Testing and Test Tools co..
- Information for people with..
- Testing Blog
- QASTREET.COM
- Bret Pettichord
- Tester Center
- I. M. Testy
- Glossary and Technical FAQs
- 위키독스
- Software Testing Mentor
- Martin Fowler's Bliki
- TestFocus
- Game Developers Blog
- smileson
- nihitk's blog
- The Test Management Guide
- Testing Foundations
- Grove Consultants
- 홍환민 페이지
- Free Video Tutorials about S..
- Sustainable Development
- 해리 로빈슨의 모델 기반 테스..
- 테스팅 써커스
- Home - Erik van Veenendaal
- URL metrics
- 소프트웨어 관리
- 경영학
- 자격증
- 소프트웨어 엔지니어링
- 소프트웨어 개발
- 추정
- 협업
- 경제
- 일정
- 평가모델
- Software Engineering
- 독서법
- 경영
- 책읽기
- 소프트웨어 테스트
- software testing
- 애자일