• 【python ---字典练习】索引 增删改 嵌套


    #    作业
    #写代码:有如下字典
    # 按照要求实现每一个功能
    # dict = {"k1":"v1","k2":"v2","k3":"v3"}
    # 1、请循环遍历出所有的key
    dic = {"k1":"v1","k2":"v2","k3":"v3"}
    re = dic.keys()
    for i in re:
        print(i,end=' ')
    
    # # 2, 请循环遍历出所有的value
    dic = {"k1":"v1","k2":"v2","k3":"v3"}
    re = dic.values()
    for i in re:
        print(i,end=' ')
    
    # 3、请循环遍历出所有的key和value
    dic = {"k1":"v1","k2":"v2","k3":"v3"}
    re = dic.items()
    for k,v in re:
        print(k,v,end=' ')
    
    # 4、请在字典中增加一个键值对,"k4":"v4",输出添加后的字典
    dic = {"k1":"v1","k2":"v2","k3":"v3"}
    dic['k4'] = 'v4'
    print(dic)
    
    # 5、请删除字典中键值对"k1":"v1",并输出删除后的结果
    dic = {"k1":"v1","k2":"v2","k3":"v3"}
    dic.pop('k1')
    print(dic)
    # 6、请删除字典中键"k5"对应的键值对,如果字典中不存在键"k5",则不报错,返回None
    dic = {"k1":"v1","k2":"v2","k3":"v3"}
    re = dic.pop('k5',None)
    print(re)
    
    # 7、请获取字典中"k2"对应的值
    dic = {"k1":"v1","k2":"v2","k3":"v3"}
    print(dic['k2'])
    
    # 8、请获取字典中"k6"对应的值,如果不存在,则不报错,并且让其返回None。
    dic = {"k1":"v1","k2":"v2","k3":"v3"}
    re = dic.pop('k6',None)
    print(re)
    # 9、现有dict2 = {"k1":"v11","a":"b"},通过一行操作使dict2 = {"k1":"v1","k2":"v2","k3":"v3","a":"b"}
    dict2 = {"k1":"v11","a":"b"}
    dic = {"k1":"v1","k2":"v2","k3":"v3"}
    dict2.update(dic)
    print(dict2)
    # 10.现有一个列表li = [1,2,3,'a',4,'c'],
    # 有一个字典(此字典是动态生成的,你并不知道他里面有多少键值对,所以用dic={}模拟字典;
    # 现在需要完成这样的操作:如果该字典没有"k1"这个键,那就创建
    # 这个"k1"键和对应的值(该键对应的值为空列表),并将列表li中的索引位为奇数对应的元素,
    # 添加到"k1"这个键对应的空列表中。如果该字典中有"k1"这个键,且k1对应的value是列表类型。
    # 那就将该列表li中的索引位为奇数对应的元素,添加到"k1",这个键对应的值中。
    dic = {}
    li = [1,2,3,'a',4,'c']
    if 'k1' not in dic:
        dic.setdefault('k1',[])
        for i in li:
            if li.index(i)%2 == 1:
                dic['k1'].append(i)
    else:
        if type(dic['k1']) == type([]):
            for i in li:
                if li.index(i)%2 == 1:
                    dic['k1'].append(i)
        else:
            print('字典k1,的value值类型不是列表,无法添加')
    print(dic)
    
    # 12现在有如下字典,完成一下需求:
    dic = {
        'name':'汪峰',
        'age':48,
        'wife':[{'name':'国际章','age':38}],
        'children':{'girl_first':'小苹果','girl_second':'小怡','girl_three':'顶顶'}
    }
    # 1. 获取汪峰的名字。
    # 2.获取这个字典:{'name':'国际章','age':38}。
    # 3. 获取汪峰妻子的名字。
    # 4. 获取汪峰的第三个孩子名字。
    # 1.
    print(dic['name'])
    # 2
    print(dic['wife'])
    # 3
    print(dic['wife'][0]['name'])
    # 4
    print(dic['children']['girl_three'])
    #
  • 相关阅读:
    普通PC硬盘与DVR专用硬盘主要差别
    远程监控,需要安装控件,安装前对浏览器设置如下。硬盘录像机,采集卡通用...
    SQL Server不允许进行远程连接
    远程备份(还原)SQL2000数据库
    安装MSDE时提示 实例名无效
    冰雹,刨冰,危险人物
    北京首现最严重的0day攻击方式
    孤独,寂寞,无聊
    大家平时都在做什么
    华山之旅
  • 原文地址:https://www.cnblogs.com/lxcai213/p/13330508.html
Copyright © 2020-2023  润新知