• python字典


    一、字典的概念

      字典跟列表很像,特别是表达方式通过花括号代替方括号。当然,字典的元素通过左边部分为键右边部分为值通过冒号来分割。

    二、字典的创建 

    dict1 = {'jack': 4098, 'sape': 4139,'yellow':8466}            #直接创建
    dict2 = dict([('jack',4098),('sape',4139),('yellow',8466)]) #根据元组创建
    dict3 = dict(jack=4098,sape=4139,yellow=8466) #通过键值创建
    dict4 = {i:chr(65+i) for i in range(4)} #键,值可以通过循环
    dict5 = {(k,v):k+v for k in range(2) for v in range(3)} #元组也能作为键
    print(dict1)
    print(dict2)
    print(dict3)
    print(dict4)
    print(dict5)
    输出:

    {'jack': 4098, 'sape': 4139, 'yellow': 8466}
    {'jack': 4098, 'sape': 4139, 'yellow': 8466}
    {'jack': 4098, 'sape': 4139, 'yellow': 8466}
    {0: 'A', 1: 'B', 2: 'C', 3: 'D'}
    {(0, 0): 0, (0, 1): 1, (0, 2): 2, (1, 0): 1, (1, 1): 2, (1, 2): 3}

    三、字典的添加修改删除

    dict1 = {'jack': 4098, 'sape': 4139,'yellow':8466} 
    dict1['jack'] = 4299 #修改元素
    dict1['rose'] = 4300 #添加元素
    print(dict1)
    输出:
    {'jack': 4299, 'sape': 4139, 'yellow': 8466, 'rose': 4300}

    del dict1['rose']              #删除字典元素
    dict1.clear() #清空字典
    del dict #删除字典

    四、字典的方法

    1、dict.clear()    #清空字典
    2、dict.copy() #返回字典的浅复制
    赋值、浅复制与深复制
    赋值:引用对象
    浅复制:引用对象的父对象
    深复制:引用对象的父对象及子对象,此处不做解释
    例:
    dict1 = {'jack': [4098,4100], 'sape': 4139,'yellow':8466}
    dic1 = dict1 #引用对象
    dic2 = dict1.copy() #浅拷贝
    dict1['jack'] = [4399,3300]
    dict1['red'] = 3200
    print(dic1)
    print(dic2)

    {'jack': [4399, 3300], 'sape': 4139, 'yellow': 8466, 'red': 3200}
    {'jack': [4098, 4100], 'sape': 4139, 'yellow': 8466}

    3、dict.fromkeys(seq[,value])           #创建一个新字典,以序列中的值作为键,以定义的值作为值

    seq = ('name','age','sex')
    dict1 = dict.fromkeys(seq,10)
    print(dict1)

    输出:
    {'name': 2, 'age': 2, 'sex': 2}
    4、dict.get(key,default=none)          #获取制定键的值如果不存在则返回默认值
    5、
    key in dict #是否存在键,返回true or false
    6、dict.items()
    #以列表方法返回键值的元组数组
    7、dict.keys()
    #返回以列表形式的所有的键
    8、
    dict.setdefault(key, default=None) #返回指定键的值,若不存在插入默认值,并返回默认值
    9、
    dict.update(dict2) #把指定字典的值更新到字典里
    10、dict.values() #与get方法类似,返回列表形式的所有的值
    11、dict.pop(key[,default]) #字典 pop() 方法删除字典给定键 key 所对应的值,返回值为被删除的值。key值必须给出。 否则,返回default值。
    12、dict.
    popitem() #从字典末尾开始删除键值对,如果字典空则抛错

    五、练习

    # 1、编写登录接口
    # 输入用户名密码
    # 认证成功后显示欢迎信息
    # 输错3次后锁定
    f = open('lockuser.log', 'r')
    strg = f.read()
    print(strg)
    userdict = {'yellow':123,'red':456,'bill':234}
    username = input('username:')
    failcount = 0
    if username in strg:
    failcount=3
    f.close()
    while failcount < 3:
    passwd = str(input('passwd:'))
    if username in userdict and passwd == str(userdict[username]):
    print('welcome!')
    break
    elif username not in userdict:
    print('invalid username!')
    username = input('username:')
    else:
    print('wrong passwd!')
    failcount+=1
    continue
    else:
    print('too many failed,%s is locked!'%(username))
    f = open('lockuser.log','a')
    f.write(username+'\n')
    f.close()


    # 2、编写多级菜单
    # 三级菜单
    # 可依次选择进入子菜单
    while True:
    workarea = {'浙江省':{'杭州市':['滨江区','西湖区'],'温州市':['永安区','苍南区']},
    '广东省':{'汕头市':['澄海区','潮阳区'],'潮州市':['诏安县','平和县']},
    '山东省':{'青岛市':['台南区','台北区'],'潍坊市':['烟台区','扯淡区']}}
    sheng = list(workarea.keys())
    print('1:'+sheng[0]+'\n'+'2:'+sheng[1]+'\n'+'3:'+sheng[2]+'\n')
    display = int(input('enter your choose:'))
    while True:
    if display>len(sheng):
    print('中国没有这个省,好好学学语文吧!')
    break
    else:
    shi = list(workarea[sheng[display-1]].keys())
    print('1:' + shi[0] + '\n' + '2:' + shi[1] + '\n'+'3、b')
    display2 = int(input('enter your choose:'))
    if display2 == 3:
    break
    elif display2 > len(shi):
    print(sheng[display-1]+'没有这个市,好好学学语文吧!')
    break
    else:
    qu = workarea[sheng[display-1]][shi[display2-1]]
    print('1:' + qu[0] + '\n' + '2:' + qu[1] + '\n'+'3、b')
    display3 = int(input('enter your choose:'))
    while True:
    if display3 == 3:
    break

     
     




  • 相关阅读:
    PHP is_float()、 is_double()、is_real()函数
    自动驾驶关键技术分解和流程
    自动驾驶行业内时间表和技术解析
    自动驾驶架构与实现路径
    ADAS单目摄像头行驶区域环境光检测图片标注
    多目标检测整合算法
    道路场景语义分割算法
    TTC测距算法
    TSR交通标志检测与识别
    Mobileye_EyeQ4功能和性能
  • 原文地址:https://www.cnblogs.com/huayng/p/9015193.html
Copyright © 2020-2023  润新知