python - 字典

判斷字典是否存在某個鍵:
不能判斷是否在值里面。

def handle_index():
    pass
def handle_datas():
    pass

URL_DICT = {

    "/index":handle_index,
    "/datas":handle_datas
}

if "/index" in URL_DICT:
    print("in it")
else:
    print("not in it")

實例2:

#_*_coding:utf-8_*_
# Author:


def handle_index():
    print ("I love u")

def handle_datas():
    print("I love me")

URL_DICT = {

    "/index":handle_index,
    "/datas":handle_datas
}

func = None

if "/index" in URL_DICT:
    func = URL_DICT["/index"]
    print("in it")
else:
    print("not in it")

if func:
    func()
else:
    "there is no func"

實例3:


def handle_index():
    f = open('index.html', mode='rb')
    data = f.read()
    f.close()

    return data

def handle_datas():
    print("I love me")

URL_DICT = {

    "/index":handle_index,
    "/datas":handle_datas
}

func = None

if "/index" in URL_DICT:
    func = URL_DICT["/index"]
    print("in it")
else:
    print("not in it")

if func:
    data = func()
    print(data)
else:
    "there is no func"

python字典知識點1:

dict = {
    "name":"liao",
    "pwd":"123456"
}

dict['name']  可以取出值,但是dict['names']就會報錯。
好的方法是:dict.get('name', None) 如果字典中沒有鍵name,那么就得到默認值None

如果不寫后面的None,我們也可以得到None,如果沒有的話,默認是填寫的None:
gender = request.POST.get('gender1')


字典的循環:

dict.keys()
dict.values()
dict.items()
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 1. 字典的一些知識點 字典特性可變、可存儲任意類型對象、無序 字典的生成?直接用dict 字典的排序?sorte...
    海螺上的斑點閱讀 412評論 0 0
  • 本篇將介紹Python里面的字典,更多內容請參考:Python學習指南 Python是什么? Python內置了字...
    小七奇奇閱讀 1,453評論 0 5
  • 一、字典基本操作 基本語法:dict = {'ob1':'computer', 'ob2':'mouse', 'o...
    古佛青燈度流年閱讀 2,663評論 0 1
  • 關鍵詞 python、dict、data struct、python字典、python collections、...
    speculatecat閱讀 1,064評論 0 11
  • 學習了 Python 基本的字典操作后,學習這些進階操作,讓寫出的代碼更加優雅簡潔和 pythonic 。 與字...
    追夢人物閱讀 12,863評論 10 70