字典

爲何要設立字典

1. 列表若是存儲大量數據,查詢速度比較慢

2. 列表的數據沒有關聯性

因爲列表具備以上缺點,所以python引入了一種新的數據類型:字典python

字典是一種可變的數據類型,這裏補充一下python數據類型分類,python數據類型按照不一樣的標準可分爲:可變與不可變;容器與非容器;算法

 

什麼是字典

字典是python裏惟一一種映射類型,採用鍵值對的結構來存儲數據,形式爲: {key1: value1,key2: value2}app

1. 字典的鍵必須是可hash的數據類型,鍵是惟一的,不能重複;字典的值能夠是任意的數據類型

2. 字典的鍵能夠經過hash算法映射成內存地址,所以字典的查詢速度很是快

3. 字典在3.5以前(包括3.5)是無序的,3.6之後的版本按照建立字典的順序排列

字典的建立

1 dic1 = {}
2 dic2 = dict()
3 print(type(dic1))
4 print(type(dic2))

輸出spa

<class 'dict'>
<class 'dict'>

Process finished with exit code 0

注意:code

(1){}表示建立字典而不是集合;orm

(2)dict()的建立是小括號而不是大括號,表示實例化一個字典對象對象

小結

字典的幾種建立方式:blog

1. dic = {"name": "Ara", "age": 18}索引

2. dic = dict()內存

  dic = dict({"name": "Ara", "age": 18})

  dic = dict(name="Ara", age=18)

3. dic.fromkeys("abc", "123")

4. dic = [[1, "a"], [2, "b"], [3, "c"]]   # 子列表或元組的長度必須是2

    dic = ((1, "a"), (2, "b"), (3, "c"))

字典的增刪改查

1. 增

按照索引添加

有則覆蓋,無則建立

1 dic = {1: "a", 2: "b", 3: "c"}
2 dic[1] = "A"
3 print(dic)
4 dic[4] = "d"
5 print(dic)

輸出

{1: 'A', 2: 'b', 3: 'c'}
{1: 'A', 2: 'b', 3: 'c', 4: 'd'}

Process finished with exit code 0

 

setdefault 添加

有則不變,無則建立

1 dic = {1: "a", 2: "b", 3: "c"}
2 dic.setdefault(2, "B")
3 print(dic)
4 dic.setdefault(4, "d")
5 print(dic)

輸出

{1: 'a', 2: 'b', 3: 'c'}
{1: 'a', 2: 'b', 3: 'c', 4: 'd'}

Process finished with exit code 0

 

2. 刪

pop

dic.pop(k,a)   刪除k對應的鍵值對,返回刪除的值(注意只有值,而不是鍵值對,pop必須指定索引

刪除k,若是沒有此鍵就返回a,若是不設置a找不到k會報錯

1 dic = {1: "a", 2: "b", 3: "c"}
2 print(dic.pop(4))
3 print(dic)

輸出

Traceback (most recent call last):
  File "D:/字典.py", line 30, in <module>
    print(dic.pop(4))
KeyError: 4

Process finished with exit code 1

 

設置k和 a

1 dic = {1: "a", 2: "b", 3: "c"}
2 print(dic.pop(2, "沒有此鍵"))
3 print(dic)
4 print(dic.pop(4, "沒有此鍵"))
5 print(dic)

輸出

b
{1: 'a', 3: 'c'}
沒有此鍵
{1: 'a', 3: 'c'}

Process finished with exit code 0

clear

dic.clear()   清空字典

1 dic = {1: "a", 2: "b", 3: "c"}
2 dic.clear()
3 print(dic)

輸出

{}

Process finished with exit code 0

popitem 

刪除最後一個鍵值對,以元組的形式返回刪除的鍵值對,3.5以前是隨機刪除,3.6以後是刪除最後一個,只能刪除最後一個,不能選定k來刪除

1 dic = {1: "a", 2: "b", 3: "c"}
2 print(dic.popitem())
3 print(dic)

輸出

(3, 'c')
{1: 'a', 2: 'b'}

Process finished with exit code 0

del

del dic1  刪除整個字典

1 dic = {1: "a", 2: "b", 3: "c"}
2 del dic
3 print(dic)

輸出

Traceback (most recent call last):
  File "D:/字典.py", line 44, in <module>
    print(dic)
NameError: name 'dic' is not defined

Process finished with exit code 1

注意清空是刪除字典裏的元素,字典還在,刪除是完全刪除整個字典,回收其內存空間

 

del也能夠按照鍵來刪,格式爲del dic[key]

1 dic = {"name": "王大錘", "age": 18, "hobby": "吹牛"}
2 del dic["age"]
3 print(dic)

輸出

{'name': '王大錘', 'hobby': '吹牛'}

Process finished with exit code 0

 

3. 改

update

dic2.update(dic1)   將dic1的數據覆蓋添加到dic2中(原來有的就覆蓋,沒有就添加)

1 dic1 = {1: "a", 2: "b", 3: "c"}
2 dic2 = {1: "A", 3: "c", "name": "夏洛", "age": "18", "hometown": "西紅柿"}
3 dic1.update(dic2)
4 print(dic1)

輸出

{1: 'A', 2: 'b', 3: 'c', 'name': '夏洛', 'age': '18', 'hometown': '西紅柿'}

Process finished with exit code 0

 

dic2.update(name="", )  關鍵字參數更改

1 dic1 = {1: "a", 2: "b", 3: "c", "name": "夏洛", "age": "18", "hometown": "西紅柿"}
2 dic1.update(name="馬冬梅", hometown="西虹市")
3 print(dic1)

輸出

{1: 'a', 2: 'b', 3: 'c', 'name': '馬冬梅', 'age': '18', 'hometown': '西虹市'}

Process finished with exit code 0

 按照索引改

按照索引找到而後賦值

4. 查

按照鍵查對應的值,找不到鍵會報錯

1 dic1 = {1: "a", 2: "b", 3: "c", "name": "夏洛", "age": "18", "hometown": "西紅柿"}
2 print(dic1["name"])
3 print(dic1["d"])

輸出

Traceback (most recent call last):
夏洛
  File "D:/字典.py", line 58, in <module>
    print(dic1["d"])
KeyError: 'd'

Process finished with exit code 1

 

get

dic.get(key, a)  找不到key就返回設定的值a

1 dic1 = {1: "a", 2: "b", 3: "c", "name": "夏洛", "age": "18", "hometown": "西紅柿"}
2 print(dic1.get(3, -1))
3 print(dic1.get(4, -1))
4 print(dic1.get(4, "未找到此鍵"))

輸出

c
-1
未找到此鍵

Process finished with exit code 0

循環遍歷

(1)直接循環(獲取的是key)

for i in dic:

    print(i)

(2)在dic.keys裏循環

for i in dic.keys():

    print(i)       # 打印key

(3)在dic.values()裏循環

for i in dic.values():

    print(i)       # 打印value

(4)在dic.items()裏循環  

for i in dic.items():    

    print(i)       # 打印鍵值對

for k, v in dic.items():

    print(k)     # 打印鍵

這裏有一個小知識點-----分別賦值(複合賦值)

用yi

5. fromkeys()建立字典

將一個可迭代對象的元素做爲key建立字典(值都同樣)

1 dic1 = dict.fromkeys("hello", "$$$")
2 print(dic1)
3 dic2 = dict.fromkeys([1, 2, 3], "$$$")
4 print(dic2)

輸出

{'h': '$$$', 'e': '$$$', 'l': '$$$', 'o': '$$$'}
{1: '$$$', 2: '$$$', 3: '$$$'}

Process finished with exit code 0

當值是可變數據類型時,經過fromkeys建立的字典的值是同一個內存地址

1 dic3 = dict.fromkeys("123", ["a", "b", "c"])
2 print(dic3)
3 dic3["3"].append("d")
4 print(dic3)

輸出

{'1': ['a', 'b', 'c'], '2': ['a', 'b', 'c'], '3': ['a', 'b', 'c']}
{'1': ['a', 'b', 'c', 'd'], '2': ['a', 'b', 'c', 'd'], '3': ['a', 'b', 'c', 'd']}

Process finished with exit code 0

能夠看到上述經過fromkeys建立的字典裏面的的列表是指向同一個內存地址的,一個發生改變,其他的也跟着改變

字典用於格式化輸出 

以前學的字符串用於格式化輸出的有%s和format,咱們回顧一下用法

1 msg = "我叫%s,今年%s, 愛好%s" % ("王大錘", 18, "吹牛")
2 print(msg)
3 
4 msg = "我叫{},今年{}, 愛好{}".format("王大錘", 18, "吹牛")
5 print(msg)
6 
7 msg = "我叫{name},今年{age}, 愛好{hobby}".format(name="王大錘", age=18, hobby="吹牛")
8 print(msg)

輸出

我叫王大錘,今年18, 愛好吹牛
我叫王大錘,今年18, 愛好吹牛
我叫王大錘,今年18, 愛好吹牛

Process finished with exit code 0

利用字典也能夠實現相似的功能,;來看代碼

1 dic = {"name": "王大錘", "age": 18, "hobby": "吹牛"}
2 msg = "我叫%(name)s,今年%(age)s, 愛好%(hobby)s" % dic   # 把佔位符後面括號裏的鍵換成對應的值,造成格式化輸出
3 print(msg)

輸出

我叫王大錘,今年18, 愛好吹牛

Process finished with exit code 0
相關文章
相關標籤/搜索
本站公眾號
   歡迎關注本站公眾號,獲取更多信息