zoukankan      html  css  js  c++  java
  • python-字典的使用


    #字典key:value
    info = {'stu1101':{'yangyang':['lan','chou']},'stu1102':'liangyan','stu1103':'yangboyu','stu1104':'liangshuang'}
    #字典是无序的,且key值必须是唯一的
    print(info['stu1101'])#通过key值查询对应value值
    info['stu1101']='杨洋'#修改key值为stu1101的value值

    #del删除
    del info['stu1101']#删除key为stu1101的值
    info.pop('stu1102')#同上
    info.popitem()#随机删一个

    print(info)


    info = {'stu1101':'yangyang','stu1102':'liangyan','stu1103':'yangboyu','stu1104':'liangshuang'}
    # print(info['stu1105'])#查询key值为stu1105的值,若不存在则报错
    print(info.get('stu1105'))#通过这种方法去取值,如果没有返回none,不会报错,上面方法会报错
    print('stu1105' in info)#查询key值是否在字典里,返回True or False,
    print(info.has_key('stu1101'))#与上面命令相同

    print(info)



    #key不要写中文
    info = {'stu1101':{'yangyang':['lan','chou']},'stu1102':'liangyan','stu1103':'yangboyu','stu1104':'liangshuang'}

    info['stu1101']['yangyang'][1] = 'ai'#修改值
    print(info.values())#打印所有value值
    print(info.keys())#打印所有key值
    info.setdefault('stu1104',{'liangxing':['gao','shou']})#如果不存在,则创建,存在,则不执行
    print info


    b = {
    'stu1101':'alex',
    1:3,
    2:5
    }
    info.update(b)#吧两个字典合并,有交叉就覆盖,没有就创建

    print info.items()#把字典转换成列表
    c = dict.fromkeys([6,7,8],[1,2,3])#初始化一个字典,前面是key,后面是值,所有key值都对应同一个value值
    print c


    for i in info:
    print i,info[i]

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

    #当列表里的值为tuple,那么循环取值时,当for后面有一个变量,就取tuple,当多余1个变量,那么变量个数就必须与tuple里值个数一至,且各tuple之间也必须存在相同个数的值
    list = [(1,'one'),(2,'two'),(3,'shree')]
    for i,k in list:
    print i,k

    print dict(list)#将list变为字段



  • 相关阅读:
    hdu 1426(DFS+坑爹的输入输出)
    hdu 1430(BFS+康托展开+映射+输出路径)
    hdu 1664(数论+同余搜索+记录路径)
    BestCoder Round #86 二,三题题解(尺取法)
    hdu 1226(同余搜索)
    poj 1426(同余搜索)
    poj 2251(同余)
    hdu 1044(bfs+dfs+剪枝)
    hdu 1455(DFS+好题+经典)
    安装centos7后不能联网
  • 原文地址:https://www.cnblogs.com/liangyan-1989/p/8184852.html
Copyright © 2011-2022 走看看