dictionary

Dictionary

1、字典的簡單介紹

  • 字典(dict)是python中惟一的一個映射類型。是以{ }括起來的鍵值對組成。
  • 字典(dict)中key必須是不可變的,而value沒有要求,能夠保存任意類型的數據。

1)字典的保存原理:

    字典在保存的時候,採用的是hash算法:根據key來計算出一個內存地址,而後將key-value保存在這個地址中。因此,在dict中存儲的key-value中的key必須是可hash的。python

    對於可hash,暫能夠理解爲能夠改變的都是不可hash的,那麼可哈希就意味着不可變,這個是爲了能準確的計算內存地址而規定的。算法

  • 已知的可hash(不可變)的數據類型:int, str, tuple, bool
  • 不可hash(可變)的數據類型:list, dict, set
  • dict保存的數據不是按照咱們添加進去的順序保存的,是按照hash表的順序保存的,而hash表不是連續的。因此不能進行切片工做,只能經過key來獲取dict中的數據。
dic = {"name": "Tom", "age": 18}

print(dic[name]) # Tom

2、字典的增刪改查

  • dic[key] = value

     若字典中無此key,則添加鍵值對,若字典中有此key,則爲修改value內容app

dic = {"name": "Tom", "age":18}

dic["hobby"] = "football" 
print(dic)  # {"name": "Tom", "age": 18, "hobby": "football"}  增長鍵-值對
dic = {"name": "Tom", "age": 18}

dic["age"] = 20
print(dic) # {"name": "Tom", "age": 20} 修改value內容
 
  • setdefault

流程:spa

a) 判斷key是否存在,若是存在,就不執行新增,返回key對應value內容code

b) 若是不存在,執行新增,並返回key對應value內容blog

dic = {"name": "Tom", "age": 18}

ret = dic.setdefault("hobby", "football")
print(dic)  # {"name": "Tom", "age": 18, "hobby": "football"}
print(ret)  # football
dic = {"name": "Tom", "age": 18}

ret = dic.setdefault("name", "Andy")
print(dic)  # {"name": "Tom", "age": 18}
print(ret)  # Tom

當採用setdefault方法新增鍵值對時,若只提供key,則默認value爲None內存

dic = {"name": "Tom", "age": 18}

dic.setdefault("hobby")
print(dic) # {"name": "Tom", "age": 18, "hobby": None}

  • pop

根據key刪除,有返回值get

dic = {"name": "Tom", "age": 18, "hobby": "football"}

ret = dic.pop("hobby")
print(dic)  # {"name": "Tom", "age": 18}
print(ret) # football
  • popitem

隨機刪除(3.5如下爲隨機刪除,3.5以上爲刪除末尾的,但python底層爲隨機刪除)hash

dic = {"name": "Tom", "age": 18, "hobby": "football"}

dic.popitem()
print(dic)  # {"name": "Tom", "age": 18}
  • del
根據key刪除
dic = {"name": "Tom", "age": 18, "hobby": "football"}

del dic["hobby"]
print(dic)  # {"name": "Tom", "age": 18}
  • clear

清空字典it

dic = {"name": "Tom", "age": 18, "hobby": "football"}

dic.clear()
print(dic)  # {}

  • dic[key] = value
dic = {"name": "Tom", "age": 18, "hobby": "football"}

dic["age"] = 20
print(dic) # {"name": "Tom", "age": 20, "hobby": "football"}
  • update

 dic.update(dic1):把dic1中的內容更新到dic中。若是key重名,則修改替換,若是不存在,則新增

dic = {"name": "Tom", "age": 18}
dic1 = {"name": "Andy", "hobby": "football"}

dic.update(dic1)

print(dic) # {"name": "Andy", "age": 18, "hobby": "football"}
print(dic1) # {"name": "Andy", "hobby": "football"}

  • print(dic[key])

當key不存在時,報錯

dic = {"name": "Tom", "age": 18, "hobby": "football"}

print(dic["name"])  # Tom
  • get

當key不存在時,返回None

dic = {"name": "Tom", "age": 18, "hobby": "football"}


print(dic.get("name")) # Tom
print(dic.get("addr")) # None
  • setdefault

當key存在時,則返回value值,但當key不存在時,則新增key-value對。

dic = {"name": "Tom", "age": 18, "hobby": "football"}

print(dic.setdefault("name")) # Tom

 3、其餘相關操做

dic.keys()

遍歷字典全部key:

for k in dic.keys():
    print(k)
for k in dic:
    print(k)
    print(dic[k]) 

dic.values()

遍歷字典全部value:

for v in dic.values():
    print(v)

dic.items()

遍歷字典的最好方案:

for k, v in dic.items():
    print(k, v)

 fromkeys

  • fromkeys屬於類dict的一個靜態方法
  • 建立新字典,不是在原有基礎上增長鍵值對
  • 若是value爲可變數據數據。則全部key均可改動這個數據,一旦改動,全部的value跟着改變
dic = dict.fromkeys(["name_1", "name_2"], [11, 22, 33])

print(dic) # {'name_1': [11, 22, 33], 'name_2': [11, 22, 33]}
dic = dict.fromkeys(["name_1", "name_2"], [11, 22, 33])

dic['name_1'].append("hello")

print(dic) # {'name_1': [11, 22, 33, 'hello'], 'name_2': [11, 22, 33, 'hello']}

4、dict在迭代過程當中刪除元素問題

dict中元素在迭代過程當中刪除,則報錯

dic = {"name": "Tom", "age": 18}

for k in dic:
    del dic[k]  # RuntimeError: dictionary changed size during iteration

解決方案

    能夠先把要刪除的元素保存在一個list中,而後循環list,刪除字典中元素

dic = {'k1': 11, "k2": 22, "s1": 33, "s2": 44}

lst = []
for k in dic:
    if "k" in k:
        lst.append(k)

for i in lst:
    del dic[i]

print(dic)  # {'s1': 33, 's2': 44}

5、字典嵌套

字典裏能夠嵌套多層列表、字典

dic = {
        "name": "Tom",
        "age": 30,    
        "hobby": ["football", "baseball"],
        "wife": {
                "name": "Andy",
                "age": "28",
        }
}

print(dic.get("wife").get("name")) # Andy
print(dic["hobby"][1])  # baseball
相關文章
相關標籤/搜索