//2018.11.6
Python字典操作
1、對於python編程里面字典的定義有以下幾種方法:
>>> a = dict(one=1, two=2, three=3)
>>> b = {'one': 1, 'two': 2, 'three': 3}
>>> C=dict(((q1,”one”),(q2,”two”)))
>>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
>>> d = dict([('two', 2), ('one', 1), ('three', 3)])
>>> e = dict({'three': 3, 'one': 1, 'two': 2})
2、 字典屬於一種映射關系,類似於數學里面的函數,可以做到一一對應,其標准格式為:
D={keys:value}
3、字典操作大全:
Dict1[x] //查詢字典里x所對應的value
Dict1.pop(m) //清除字典里m元素對應的一組
Dict1.popitem() //清除字典里的一對元素,隨機刪除
Dict1.clear() //清空字典
M={“a”:”b”}
Dict1.update(m) //更新和添加字典元素
Dict1.get(x) //輸出x對應的映射元素
Dict1.fromkeys((1,2,3),"number") //給1/2/3賦予相同的映射結果:“number”
Dict1.copy() //深拷貝字典
a in Dict1: //判斷a是否為字典里的元素key
如下圖所示:
4、通訊錄程序舉例:
實現以下功能:
具體程序如下:
print("|---歡迎進入通訊錄程序---|")
print("|---1:查詢聯系人資料 ---|")
print("|---2:插入新的聯系人 ---|")
print("|---3:刪除已有聯系人 ---|")
print("|---4:退出通訊錄程序 ---|")
d={"小甲魚":"020-88974651"}
Q=1
while (Q):
a=input("請輸入相關的指令代碼:")
if a=="1":
b=input("請輸入聯系人姓名:")
print(b,":",d[b])
elif a=="2":
b=input("請輸入聯系人姓名:")
if b in d:
print("您輸入的姓名已在通訊錄中存在-->>",b,":",d[b])
x=input("是否需要修改用戶資料(YES/NO):")
if x=="YES":
y=input("請輸入用戶聯系電話:")
W={b:y}
d.update(W)
print(d)
else:
print("返回程序")
else:
c=input("請輸入用戶聯系人電話:")
d[b]=c
print(d)
elif a=="3":
b=input("請輸入刪除聯系人姓名:")
d.pop(b)
print(d)
else:
print("|---感謝使用通訊錄---|")
Q=0