Python中,字典(dict) 是一種內置的映射類型,也是惟一的;字典由鍵及其相應的值組成,這種鍵-值對
稱爲項(item)。
字典基礎
定義
dict1 = {} # 空字典
# python 是完全動態數據類型,同一個字典Value類型可以是多種的
dict2 = {'name': 'python3.7', 'age': 19, 'website': 'http://www.python.org'}
print(dict2) # {'name': 'python3.7', 'age': 19, 'website': 'http://www.python.org'}
獲取項數(鍵-值對數)
length = len(dict2)
print(length) # 3
刪除項
del dict2['website'] # 通過key刪除項
# dict2.clear() # 刪除掉所有項
print(dict2) # {'name': 'python3.7', 'age': 19}
添加項
dict2['website'] = 'http://www.python.org'
print(dict2) # {'name': 'python3.7', 'age': 19, 'website': 'http://www.python.org'}
修改值
dict2['website'] = 'http://python.org' # 通過key修改值
print(dict2) # {'name': 'python3.7', 'age': 19, 'website': 'http://python.org'}
獲取值
website = dict2['website'] # 通過 key 獲取值
print(website) # http://python.org
獲取所有 key
keys = dict2.keys()
print(keys) # dict_keys(['name', 'age', 'website'])
# 排序後獲取到的是list
keys = sorted(dict2.keys())
print(keys) # ['age', 'name', 'website']
獲取所有 value
values = dict2.values()
print(values) # dict_values(['python3.7', 19, 'http://python.org'])
字典升階
判斷 key 在字典中是否存在
if 'mykey' in dict2:
print('字典中存在 `mykey`')
if 'mykey' not in dict2:
print('字典中不存在 `mykey`')
遍歷字典
# 遍歷 key
for key in dict2:
value = dict2[key]
print(key, value)
# 遍歷 value
for value in dict2.values():
print(value)
# 遍歷 key,value
for key, value in dict2.items():
print(key, value)
將字符串格式設置功能用於字典
# format_map 會自動查找與參數名一樣的key,並獲取值
desc = 'python home is {website}'.format_map(dict2)
print(desc) # python home is http://python.org
desc = '{name} home is {website}'.format_map(dict2)
print(desc) # python3.7 home is http://python.org