DAY 8
0

## Day -11 字典

• 字典常用方法
``````tel = {'jack': 4098, 'sape': 4139}
print(tel)
//新增一組key/value
tel['guido'] = 4127
print(tel)
print(tel['jack'])

//刪除一組字典中 key sape
del tel['sape']
print(tel)
tel['irv'] = 4127
print(tel)

//list 顯示
print(list(tel))
//list 顯示 字母排序
print(sorted(tel))

//判斷  value 是否在 tel 字典
a ='guido' in tel
print(a)
b = 'jack' not in tel
print(b)

-----------------print ------------------------
{'jack': 4098, 'sape': 4139}
{'jack': 4098, 'sape': 4139, 'guido': 4127}
4098
{'jack': 4098, 'guido': 4127}
{'jack': 4098, 'guido': 4127, 'irv': 4127}
['jack', 'guido', 'irv']
['guido', 'irv', 'jack']
True
False
``````
• 字典宣告方式
``````
tel = dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
print(tel)

tel = {x: x**2 for x in (2, 4, 6)}
print(tel)

tel = dict(sape=4139, guido=4127, jack=4098)
print(tel)
-----------------print ------------------------
{'sape': 4139, 'guido': 4127, 'jack': 4098}
{2: 4, 4: 16, 6: 36}
{'sape': 4139, 'guido': 4127, 'jack': 4098}
``````

-應用於迴圈

``````knights = {'gallahad': 'the pure', 'robin': 'the brave'}

// 字典 中 key/value
for k, v in knights.items():
print(k, v)

// 索引序列
for i, v in enumerate(knights):
print(i, v)

// list 合併成字典
questions = ['name', 'quest', 'favorite color']
answers = ['lancelot', 'the holy grail', 'blue']
for q, a in zip(questions, answers):
print('What is your {0}?  It is {1}.'.format(q, a))

-----------------print ------------------------
robin the brave
1 robin
What is your name?  It is lancelot.
What is your quest?  It is the holy grail.
What is your favorite color?  It is blue.

``````

ref:
docs.python.org

Python 基礎學習之旅12