python 字典基本操作

2022-08-22 13:03:15 字數 3780 閱讀 4597

格式key  :value

# string list dict

#  1

、取資料方便

# 2、速度快,

定義乙個空字典:

d = dict()

或者 d =

infos  =  #查

print(infos.get('phone'))#

取不到這個

key的話,就是

none

print(infos.get('phone',110))#

如果取不到這個

key的話,預設就是

110print(infos['phone'])#

如果key

不存在會報錯#增

infos['phone']=13611087045 #

增加乙個

keyinfos.setdefault('小金庫','2000w')

infos.setdefault('name','鵬妹妹') #

如果key

存在的話,不會修改原來

key裡面的值

infos['name']='鵬妹妹1'#

如果key

存在的話,會修改原來

key對應的

value

print(infos)

# #字典是無序的

# #修改

infos['name']='鵬妹妹'

print(infos)

# 刪除

infos.pop('name') #

指定key

來刪除print(infos)

infos.popitem() #

隨機刪除乙個

keyprint(infos)

delinfos['phone'] #

指定key

來刪除print(infos)

infos.clear()  #

清空字典

print(infos)

# #方法

print(infos.values())#

獲取到字典所有的

value

print(infos.keys()) #

獲取到字典所有的

keyprint(infos.items()) #

獲取字典所有的

k-v字典練習

people = ,

'張流量':}}

people['張流量牧馬人')

people['田雨匡威')

print(people)

people['田雨']['money'] = people['田雨']['money']+200

people['田雨']['money'] += 200

print(people)

# #直接迴圈乙個字典的話,那麼迴圈的是字典的

keyforpinpeople:

print(p)

fork,vinpeople.items():  #

迴圈的時候,同時取

key和

value

print(k,'*****=',v)

練習2users =

#所有的賬號和密碼

# username

# pwd

# cpwd

# print( '123456' in users )   #

字典裡面用

in來判斷的話,只是判斷

key是否存在

foriinrange(3):

username = input('賬號:').strip()

passwd = input('密碼:').strip()

cpasswd = input('密碼確定:').strip()

ifusername==''orpasswd==''orcpasswd=='':

print('使用者名稱/密碼不能為空')

elifusernameinusers:

print('使用者名稱已經被註冊!')

elifpasswd!=cpasswd:

print('兩次輸入的密碼不一致')

else:

print('恭喜,註冊成功!')

# users.setdefault(username,passwd)

users[username]=passwd

break

else:

print('錯誤次數過多')

print(users)

python 字典基本操作

一,對字典的基本定義 dict1 dict2 二 如何訪問字典中的值 所有例子,均使用python3進行除錯 dict1 for key in dict1 print s s key,dict1 key 輸出為 name joe value 12 三 給字典賦值 dict1 money 15000 ...

Python字典基本操作

除了使用key查詢資料,還可以使用get來獲取資料 demo info print info age 獲取年齡 print info 獲取不存在的key,會發生異常 print info.get 獲取不存在的key,獲取到空的內容,不會出現異常 字典的每個元素中的資料是可以修改的,只要通過key找到...

Python字典的基本操作

1.建立字典 使用花括號,也使用內建 函式dict zidian dict color red points 5 zidian zidian1 dict color red points 5 2.新增和修改字典 我們通過dict key value來實現 修改字典 zidian dict color...