Python學習第三天 字典

2021-10-06 02:38:29 字數 2455 閱讀 5002

在《python程式設計從入門到實踐中》用乙個遊戲來解釋了python中字典的各種用法。

先建立乙個簡單的字典:

alien_0=

print(alien_0['color'])

print(alien_0['points'])

print(alien_0)

output:

green

5

而要修改字典中的值,可以依次指定字典名字,用方括號括起的鍵以及與該鍵相關的新值

例如,將外星人的顏色改為黃色

alien_0=

print("the alien is "+alien_0['color']+".")

alien_0['color']= 'yellow'

print("the alien is now "+alien_0['color']+".")

the alien is green.

the alien is now yellow.

再來看乙個更有趣的例子:對於乙個能以不同速度移動的外星人的位置進行追蹤。

alien_0=

print

("original x-position : "

+str

(alien_0[

'x_position'])

)if alien_0[

'speed']==

'slow'

: x_increment=

1elif alien_0[

'speed']==

'medium'

: x_increment=

2else

: x_increment=

3alien_0[

'x_position'

]=alien_0[

'x_position'

]+x_increment

print

("new x-position is "

+str

(alien_0[

'x_position'])

)

original x-position : 0

new x-position is 2

如果要刪除字典中的鍵-值對可以使用del

alien_0=

print

(alien_0)

del alien_0[

'point'

]print

(alien_0)

user_0=

for key,value in user_0.items():

print

("\nkey: "

+key)

print

("value: "

+value)

key: usersname

value: efermi

key: first

value: enrico

key: last

value: fermi

這裡要注意,在遍歷字典時,鍵-值對返回的順序與存貯順序不同。python不關心鍵-值對的儲存順序只跟蹤鍵值的關聯關係。

user_0=

for key in user_0.keys():

print

(key.title(

))

usersname

first

last

由於遍歷列表時會預設遍歷所有的鍵,因此如果將

for key in user_0.keys():換成for key in user_0():結果不變。

順序遍歷字典中的所有的鍵:

user_0=

for key in

sorted

(user_0.keys())

:print

(key.title(

))

first

last

usersname

user_0=

for value in user_0.values():

print

(value)

efermi

enrico

fermi

由於字典中的值會有重複,因此可以使用set()剔除重複的項

CSS學習第三天 字型

指定字型 選擇器 如果讀者沒有安裝 georgia,但安裝了 times 字型 serif 字型系列中的一種字型 使用者 就可能對 h1 元素使用 times。儘管 times 與 georgia 並不完全匹配,但至少足夠接近。因此,我們建議在所有 font family 規則中都提供乙個通用字型系...

Python 第三天 字串

常見的基本資料型別 1.int 整數 2.bool 布林.判斷.if while 3.str 字串,一般放小量的資料.4.list 列表.可以存放大量的資料 5.dict 字典,以key value的形式儲存資料 6.set 集合 數學 7.tuple 元組 不可變 1.int 整數 常見操作就那麼...

學習python 第三天

python的分支結構 if語句 在python中,要構造分支結構可以使用if elif和else 驗證 answer input 請輸入使用者名稱 if answer a print 回答成功 else print 回答失敗 如果要構造出更多的分支,可以使用if elif else 結構 多次驗證...