分分鐘鐘學會Python - 數據類型(dict)
阿新 • • 發佈:2019-04-20
類型 事物 put ear 用戶名 循環 uno pytho 輸入密碼
今日內容
字典(dict)
具體內容
1.字典含義
幫助用戶去表示一個事物的信息(事物是有多個屬性)。
基本格式
data = {鍵:值,鍵:值,鍵:值,鍵:值,鍵:值,鍵:值,}
# 練習題 userinfo = {'usenrame':'li','password':"xiangmin"} user = input('請輸入用戶:') pwd = input('請輸入密碼:') if userinfo['username'] == user and userinfo['password'] == pwd: print('登陸成功') else: print('用戶名或密碼錯誤')
2.獨有方法
info = {"name":'li','age':18,'gender':'男',}
1.".keys" ,獲取字典中所有的鍵
for item in info.keys(): print(item) #循環獲取字典中所有的鍵
2.".values" ,獲取字典中所有的值
for item in info.values(): print(item) #循環獲取字典中所有的鍵
3.".items" ,獲取字典中的所有鍵值對。
del info['gender'] print(info) # {'name': 'li', 'age': 18}
4.".get" ,函數返回指定鍵的值,如果值不在字典中返回默認值。
# 示例 一 dict = {'Name': 'Zara', 'Age': 27} print(dict.get('Age')) # 27 # 示例 二 dict = {'Name': 'Zara', 'Age': 27} print(dict.get('asd')) # None print(dict.get('asd',"123")) # 123
5.".update" ,更新,字典裏不存在增加/存在更新
# 示例 一 dict = {'Name': 'Runoob', 'Age': 7} a = {'Age':9} dict.update(a) print(dict) # {'Name': 'Runoob', 'Age': 9} # 示例 二 dict = {'Name': 'Runoob', 'Age': 7} dict2 = {'Sex': 'female'} dict.update(dict2) print("更新字典 dict :- ", dict)
6."del" ,刪除 -#鍵值對一個整體,要刪全刪
".pop" ,刪除
".clear",刪除(清空所有內容)
info = {"name":'li','age':18,'gender':'男',} # 方法一 del info['gender'] print(info) # {'name': 'li', 'age': 18} # 方法二 a = info.pop('name') print(info) # {'age': 18, 'gender': '男'} # 方法三 info.clear() print(info) # {}
3.公共方法
1.len
info = {"name":'li','age':18,'gender':'男',} print(len(info)) # 3
2.索引
info = {"name":'li','age':18,'gender':'男',} a = info['name'] b = info['age'] print(a) # li print(b) # 18
3.for 循環
info = {"name":'li','age':18,'gender':'男',} for a in info.keys(): print(a) # 循環打印出所有鍵 for b in info.values(): print(b) # 循環打印出所有值 for c,d in info.items(): print(c,d) # 循環打印出所有鍵值
4.修改 #存在就修改/不存在就增加
# 改值 info = {"name":'li','age':18,'gender':'男',} info['age'] = 99 print(info) # {'name': 'li', 'age': 99, 'gender': '男'} # 改鍵 # 刪除後再增加 del info['gender'] print(info) # {'name': 'li', 'age': 18} info['asd'] = '123' print(info) # {'name': 'li', 'age': 18, 'asd': '123'}
分分鐘鐘學會Python - 數據類型(dict)