Python字典常用的定義方法
-
直接定義一個字典
dict1 = {'x': 1, 'y': 2, 'z': 3} -
利用dict方法定義一個字典
dict2 = dict(x=1, y=2, z=3) -
利用dict方法定義一個字典
dict3 = dict((('x', 1), ('y', 2), ('z', 3))) - dict內建方法fromkeys創建並返回一個新字典
dict4 = dict4.fromkeys('x', '1')
也可以用循環的方式生成字典:dict4.fromkeys(range(10), 'good'), 生成結果爲 {0: 'good', 1: 'good', 2: 'good', 3: 'good', 4: 'good', 5: 'good', 6: 'good', 7: 'good', 8: 'good', 9: 'good'}
字典的常用方法
dict1.clear() 清空一個字典,結果返回一個空字典 {}
dict1.copy() 字典的淺拷貝,不同於賦值
例如:
dict1 = {'x':1, 'y':2, 'z':3}
dict2 = dict1.copy(), 則dict2 = {'x':1, 'y':2, 'z':3}
dict3 = dict1, 採用賦值的方法,則修改dict3會影響dict1
如, dict3['w'] = 666, dict3返回結果爲{'x': 1, 'y': 2, 'z': 3, 'w': 666}, dict1也返回{'x': 1, 'y': 2, 'z': 3, 'w': 666}
但修改dict2不影響dict1,如:dict2['v'] = 88,則dict2返回{'x': 1, 'y': 2, 'z': 3, 'v': 88},而dict1依然返回{'x': 1, 'y': 2, 'z': 3, 'w': 666}
dict1.pop('x') 從字典中刪除‘x'鍵和對應的值並返回該值
del dict1['x'] 也可以刪除鍵'x'
dict1.popitem() 隨機從字典中刪除一個數據
dict1.keys() 返回字典中的所有鍵的列表,
>>> dict3.keys()
dict_keys(['x', 'y', 'z'])
dict1.values()返回字典中的所有值
>>> print(dict3.values())
dict_values([1, 2, 3])
dict1.items() 將字典的key, value分成成對形式的元組
>>> dict2.items()
dict_items([('x', 1), ('y', 2), ('z', 3)])
dict1.setdefault('w') 爲字典加入一個值並賦值爲默認值,dict1.setdefault('w'),返回{'w': None}
dict1.get('w'),返回鍵“w"的值,若"w"不存在,則返回默認值None
一些特殊用法
將2個列表元素映射爲字典
list1 = ['x', 'y', 'z']
list2 = [1, 2, 3]
dict(zip(list1,list2))
輸出結果爲 {'x': 1, 'y': 2, 'z': 3}
如果2個列表元素數量不一致,則只映射元素數量最小列表的,
如 list3 = [10, 7]
dict(zip(list1, list3))
輸出結果爲 {'x': 10, 'y': 7}
字典的生成式
映射字典 i: i2, 且i 爲2到20以內且能被3整除的數
{ i: i2 for i in range(2,20) if i % 3 == 0 } ,輸出結果爲 {3: 6, 6: 12, 9: 18, 12: 24, 15: 30, 18: 36}
利用字典建立一個簡單通訊錄程序
contact_dict = {'老王':"135", '老李':'137'}
while True:
choice = input('''請輸入選項:
1. 查詢聯繫人
2. 添加聯繫人
3. 顯示所有聯繫人
4. 刪除聯繫人
5. 退出
''')
if choice == '1':
name = input("輸入聯繫人姓名:\n")
if name in contact_dict.keys():
print("%s 的聯繫電話是 %s \n" % (name, contact_dict[name]))
else:
print("%s不存在.\n" % name)
elif choice == '2':
name = input("輸入聯繫人姓名:")
telenum = input("輸入聯繫人電話:")
contact_dict[name] = telenum
elif choice == '3':
if contact_dict.keys() == []:
print("通訊錄爲空,請添加聯繫人!")
else:
for contact_name in contact_dict.keys():
print("%s的聯繫電話是 %s" % (contact_name, contact_dict[contact_name]))
elif choice == '4':
name = input("輸入聯繫人姓名:")
contact_dict.pop(name)
elif choice == '5':
break
else:
print("輸入錯誤!")
continue