字典(dict) 在其他語言中被稱為哈希映射(hash map)或者相關數組,它是一種大小可變的鍵值對集,其中的key、value都是python對象。
特別注意:
1.字典中的key不能重復,key可以是任意類型
2.字典是無序的,所以不能像數組、元組一樣通過下標讀取
字典創建:
1.創建空字典
word = dict()
2.創建非空字典
words = {"rice": "米", "breakfast": "早餐", "lunch": "午餐", "dinner": "晚餐",
"bacon": "培根", "pasta": "意大利面", "have": "吃", "egg": "蛋"}
price = dict(rice= 3.44, bacon=8.99, egg=8.99, pasta=68.7) print(price)
price = dict(zip(["rice", "bacon", "egg", "pasta"], [3.44, 8.99, 8.99, 68.7])) print(price)
price = dict([("rice", 3.44), ("bacon", 8.99), ("egg", 9.99), ("pasta", 68.7)]) print(price)
字典讀取:
1.通過key讀取
print(words["egg"])
2.通過get()方法讀取-----常用
使用get()方法讀取時,當傳入一個不存在的鍵時,程序不會拋出異常,若未指定返回值則返回None,否則返回所指定值
one = words.get("rice")
print(one)
two = words.get("apple")
print(two)
three = words.get("banana", "暫無該商品")
print(three)
3.通過 setdefault()方法讀取
setdefault()方法與get()方法類似,若給定的key存在,則返回key對應的值,若不存在,值返回給定的默認值,若未指定,值默認為None,並且字典中同時添加該鍵與值
four = price.setdefault("banana", 6.99) five = price.setdefault("rice") six = price.setdefault("apple") print(four) print(five) print(six)
4.遍歷key
for key in words.keys():
print(key)
或
for key in words: #對比以上,如果不加任何方法說明,那么默認輸出的是字典中所有鍵的值 print(key)

5.遍歷value
for value in words.values():
print(value)
6.遍歷鍵值對
for item in words.items():
print(item)
for key, value in words.items(): print({key: value})
7.字典的刪除
# clear()方法清除字典中所有的元素 words.clear() print(words)
# pop()方法通過傳入key,刪除元素 words.pop("rice") print(words)
#popitem()方法隨機刪除某項鍵值對 words.popitem() print(words)
# del()方法可通過傳入的key刪除某項元素,也可直接刪除整個字典 del words["egg"] print(words)
del words print(words)
8.字典的修改
# 通過[key]插入元素 price["apple"] = 6.99 print(price)
# setdefault()方法與get()方法類似,若給定的key存在,則返回key對應的值, # 若不存在,值返回給定的默認值,若未指定,值默認為None,並且字典中同時添加該鍵與值 price.setdefault("banana", 6.99) price.setdefault("milk") print(price)
# 通過[key]修改 price["rice"] = 3.99 print(price)
# 通過update()方法修改 ---使用解包字典 price.update(**{"rice": 4.99}) # 通過update()方法修改 ---使用字典對象 price.update({"rice": 5.99}) # 通過update()方法修改 ---使用關鍵字參數 price.update(rice=6.99) print(price)




