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