iT邦幫忙

2021 iThome 鐵人賽

DAY 8
0
自我挑戰組

Python 基礎學習之旅系列 第 11

Day -11 字典

字典是Python內建的資料類型之一,值(key:value)來進行存取,定義key與value之間一對一的關係。
每一個key是獨一無二的,因此會以key來取value。故字典不在乎項目的順序,可任意排列,且字典是可變的,所以可以任意更改key/value。

以官網為例如下:

  • 字典常用方法
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 ------------------------
['gallahad', 'robin']
gallahad the pure
robin the brave
0 gallahad
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


上一篇
Day -10 tuple與List
下一篇
Day - 12 集合
系列文
Python 基礎學習之旅12

尚未有邦友留言

立即登入留言