一.字典創(chuàng)建
1創(chuàng)建字典:我們可以通過兩種方式創(chuàng)建字典:
person = {"username": "zhiliao", "age": 18}
2.或者是使用dict函數(shù):
person = dict(username='zhiliao', age=18)
二.基本操作
'''
? ? len(d):返回字典的鍵值對(duì)的長(zhǎng)度没龙。? ? d[k]:獲取k這個(gè)key對(duì)應(yīng)的值捐川。? ? d[k] = v:設(shè)置鍵為k的值為v房蝉,如果字典中不存在鍵為k的這一項(xiàng),那么自動(dòng)的添加進(jìn)去紫新。? ? del d[k]:刪除d這個(gè)字典中鍵為k的這一項(xiàng)數(shù)據(jù)。? ? k in d:檢查d這個(gè)字典中是否包含鍵為k的這一項(xiàng)熙卡。
? ? 字典中的鍵可以是任意的不可變類型芍锦,比如:浮點(diǎn)類型、整形裹虫、字符串或者元組肿嘲。
'''
三.常用方法
1.clear,清除字典中所有的項(xiàng)
person = {'username':'zhiliao','age':26}
print(person)
person.clear()
print(person)
2.get,訪問字典中那個(gè)鍵對(duì)應(yīng)的那個(gè)值。這個(gè)方法不會(huì)拋出異常筑公。
person = {'username':'zhiliao','age':26}
username = person['username']
print(username)
username2 = person.get('username')
print(username2)
3.pop,用來獲得對(duì)應(yīng)于給定鍵的值雳窟,然后將這個(gè)鍵盤和值的項(xiàng)從字典中刪除。會(huì)返回這個(gè)值
person = {'username':'zhiliao','age':26}
age = person.pop('age')
print(age)
print(person)
4.popitem(),隨機(jī)拋出字典中一項(xiàng)
person = {'username':'zhiliao','age':26}
value = person.popitem()
print(person)
print(value)
5.update,用一個(gè)字典更新另外一個(gè)字典匣屡,如果碰到相同的鍵封救,則會(huì)覆蓋。
person = {'username':'zhiliao','age':26}
person2 = {'height':180,'weight':150}
person.update(person2)
print(person)
print(person2)
person = {'username':'zhiliao','age':26}
person2 = {'height':180,'weight':150,'username':'ketang'}
person.update(person2)
print(person)
print(person2)
setdefault
如果這個(gè)鍵字典中存在捣作,則返回字典中這個(gè)鍵的值
如果這個(gè)鍵不存在誉结,會(huì)把這個(gè)鍵值對(duì)添加進(jìn)這個(gè)字典中,斌且返回這個(gè)鍵
person = {'username':'zhiliao','age':26}
username = person.setdefault('username':'ketang')
print(username)
print(person)
四.字典遍歷
1.遍歷鍵
person = {'username':'zhiliao','age':26,'height':'180','weight':'160'}
keys = person.keys()
print(keys)
for k in keys:
? ? print(k)遍歷鍵
2.遍歷值
person = {'username':'zhiliao','age':26,'height':'180','weight':'160'}
values = person.values()
print(values)
for v in values:
? ? print(v)
3.遍歷所有鍵值對(duì)
person = {'username':'zhiliao','age':26,'height':'180','weight':'160'}
itime = person.items()
print(itime)
for key,value in itime:
? ? print(key)
? ? print(value)
person = {'username':'zhiliao','age':26,'height':'180','weight':'160'}
for key,value in person.items():
? ? print("key:%s,value:%s"%(key,value))