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()

你可能感兴趣的:(python - 字典)