1.字典的创建及索引
a={'h':'hello',0.5:[0.2,0.3],'w':'world'}
print(a)
b=a[0.5] #字典中的元素无先后顺序,字典是用键来索引的
print(b)
#出现相同的键则覆盖
#列表是可修改数据类型,不能做键
{'h': 'hello', 0.5: [0.2, 0.3], 'w': 'world'}
[0.2, 0.3]
2.字典常用操作
#修改
a['h']=100
print(a)
#新增键值对
a['hw']='hello world'
print(a)
a.update({1:2,3:4}) #批量新增
print(a)
#删除
del a['h'] #删除某一键值对
print(a)
#del a #删掉整个字典 执行print会报错,因为字典已被删除
{'h': 100, 0.5: [0.2, 0.3], 'w': 'world'}
{'h': 100, 0.5: [0.2, 0.3], 'w': 'world', 'hw': 'hello world'}
{'h': 100, 0.5: [0.2, 0.3], 'w': 'world', 'hw': 'hello world', 1: 2, 3: 4}
{0.5: [0.2, 0.3], 'w': 'world', 'hw': 'hello world', 1: 2, 3: 4}
3.字典的推导式
#字典推导式
c={i:i**2 for i in range(10)}
print(c)
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}