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()
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1. 字典的一些知识点 字典特性可变、可存储任意类型对象、无序 字典的生成?直接用dict 字典的排序?sorte...
    海螺上的斑点阅读 3,106评论 0 0
  • 本篇将介绍Python里面的字典,更多内容请参考:Python学习指南 Python是什么? Python内置了字...
    小七奇奇阅读 5,274评论 0 5
  • 一、字典基本操作 基本语法:dict = {'ob1':'computer', 'ob2':'mouse', 'o...
    古佛青灯度流年阅读 7,506评论 0 1
  • 关键词 python、dict、data struct、python字典、python collections、...
    speculatecat阅读 4,697评论 0 11
  • 学习了 Python 基本的字典操作后,学习这些进阶操作,让写出的代码更加优雅简洁和 pythonic 。 与字...
    追梦人物阅读 14,379评论 10 70

友情链接更多精彩内容