• KeyError: 1


    1、错误描述

    E:PycharmProjectscmnvenvScriptspython.exe E:/PycharmProjects/cmn/venv/com.you.cmn/B.py
    1
    ('you', 2)
    (2, 'hai', 3, 'dong')
    ('hai', 3)
    (1, 'you', 2, 'hai', 3, 'dong', 1, 'you', 2, 'hai', 3, 'dong', 1, 'you', 2, 'hai', 3, 'dong', 1, 'you', 2, 'hai', 3, 'dong', 1, 'you', 2, 'hai', 3, 'dong')
    (1, 'you', 2, 'hai', 3, 'dong', 1, 2, 3, 4, 5, 6)
    Traceback (most recent call last):
      File "E:/PycharmProjects/cmn/venv/com.you.cmn/B.py", line 10, in <module>
        print(C[1]);
    KeyError: 1
    
    Process finished with exit code 1

    2、错误原因

          列表取元素,可以直接使用列表加序号或序号范围;但是,字典是键值对构成的,不能使用字典加序号取元素,需要使用字典加key值取。

    A = (1,'you',2,'hai',3,'dong');
    B = (1,2,3,4,5,6);
    C = {'name':'zhangsan','age':'23','addr':'湖北省武汉市'}
    print(A[0]);
    print(A[1:3]);
    print(A[2:]);
    print(A[-3:-1]);
    print(A*5);
    print(A + B);
    print(C[1]);
    print(C['age']);
    print(C['addr']);
    print(C.keys());
    print(C.values());

    3、解决办法

         将print(C[1])改为print(C['name'])

    A = (1,'you',2,'hai',3,'dong');
    B = (1,2,3,4,5,6);
    C = {'name':'zhangsan','age':'23','addr':'湖北省武汉市'}
    print(A[0]);
    print(A[1:3]);
    print(A[2:]);
    print(A[-3:-1]);
    print(A*5);
    print(A + B);
    print(C['name']);
    print(C['age']);
    print(C['addr']);
    print(C.keys());
    print(C.values());
    
    
    结果:
    
    E:PycharmProjectscmnvenvScriptspython.exe E:/PycharmProjects/cmn/venv/com.you.cmn/B.py
    1
    ('you', 2)
    (2, 'hai', 3, 'dong')
    ('hai', 3)
    (1, 'you', 2, 'hai', 3, 'dong', 1, 'you', 2, 'hai', 3, 'dong', 1, 'you', 2, 'hai', 3, 'dong', 1, 'you', 2, 'hai', 3, 'dong', 1, 'you', 2, 'hai', 3, 'dong')
    (1, 'you', 2, 'hai', 3, 'dong', 1, 2, 3, 4, 5, 6)
    zhangsan
    23
    湖北省武汉市
    dict_keys(['name', 'age', 'addr'])
    dict_values(['zhangsan', '23', '湖北省武汉市'])
    
    Process finished with exit code 0
  • 相关阅读:
    Spring Boot中实现logback多环境日志配置
    阿里云ECSLinux系统下挂载磁盘(转)
    解决 No qualifying bean of type 问题
    通过rpm离线安装Oracle 19C
    ADFS配置踩坑记
    .NET Core 2.0下载和文档
    .NET Core 2.0和ASP.NET Core 2.0正式版抢先体验
    .NET 微服务和Docker容器
    DocFX生成PDF文档
    ASP.NET Core 开源论坛项目 NETCoreBBS
  • 原文地址:https://www.cnblogs.com/hzcya1995/p/13313691.html
Copyright © 2020-2023  润新知