字典相关常识
info={‘k1’:‘v1’ ,‘k2’:‘v2’} (其中‘k1’:‘v1’叫键值对)
1.字典的value可以是任意值(列表、元组、字符串、数字等);列表、字典不能作为字典的key
2.字典是无序的,可以根据建进行索引,不能切片 ( tu[k1] 获得k1键对应的值)
3.字典支持删除
tu={'k1':18,2:'True','k3':[11,[],2,22,33,{'kk1':'vv1','kk2':'vv2','kk3':(22,33,)}],'k4':(11,22,33,)}
del tu['k1']
print(tu)
运行结果:{2: 'True', 'k3': [11, [], 2, 22, 33, {'kk1': 'vv1', 'kk2': 'vv2', 'kk3': (22, 33)}], 'k4': (11, 22, 33)}
4.支持for循环,
(1)默认循环所有的key,
tu={'k1':18,2:'True','k3':[11,[],2,22,33,{'kk1':'vv1','kk2':'vv2','kk3':(22,33,)}],'k4':(11,22,33,)}
for i in tu:
print(i)
运行结果:
k1
2
k3
k4
(2)可通过设置循环value
tu={'k1':18,2:'True','k3':[11,[],2,22,33,{'kk1':'vv1','kk2':'vv2','kk3':(22,33,)}],'k4':(11,22,33,)} for i in tu.values(): print(i) 运行结果: 18 True [11, [], 2, 22, 33, {'kk1': 'vv1', 'kk2': 'vv2', 'kk3': (22, 33)}] (11, 22, 33)
(3)可通过设置取得键值对
tu={'k1':18,2:'True','k3':[11,[],2,22,33,{'kk1':'vv1','kk2':'vv2','kk3':(22,33,)}],'k4':(11,22,33,)}
for i in tu.items():
print(i)
运行结果:
('k1', 18)
(2, 'True')
('k3', [11, [], 2, 22, 33, {'kk1': 'vv1', 'kk2': 'vv2', 'kk3': (22, 33)}])
('k4', (11, 22, 33))