Python中的字典用于存储 key-value(键值对)类型数据。
字典的表现形式
if __name__ == '__main__':
dict1={1:"a",2:23,4:1+5j}
dict2={"1":"j","2":2}
dict3={}
dict4={"1+2j":4,"4-5j":5}
dict5={"1+7j":4,"2":5,1:"sdfsdf"}
dict6={1:dict1,2:dict2,3:dict3,4:dict4,5:dict5}
print("dict1=",dict1)
print("dict2=",dict2)
print("dict3=",dict3)
print("dict4=",dict4)
print("dict5=",dict5)
print("dict6=",dict6)
相应输出为
dict1= {1: 'a', 2: 23, 4: (1+5j)}
dict2= {'1': 'j', '2': 2}
dict3= {}
dict4= {'1+2j': 4, '4-5j': 5}
dict5= {'1+7j': 4, '2': 5, 1: 'sdfsdf'}
dict6= {1: {1: 'a', 2: 23, 4: (1+5j)}, 2: {'1': 'j', '2': 2}, 3: {}, 4: {'1+2j': 4, '4-5j': 5}, 5: {'1+7j': 4, '2': 5, 1: 'sdfsdf'}}
(1)字典可以为空,可以嵌套
(2)key可以为任意数据类型,但必须唯一
字典元素的访问
print("dict1[1] = ", dict1[1])
print("dict2['1'] =", dict2["1"])
print("dict4.get['1+2j'] = ",dict4.get("1+2j"))
相应输出为
dict1(1) = a
dict2['1'] = j
dict4.get['1+2j'] = 4
共有两种访问方式
(1)dictname【key】
(2)dictname.get(key)
字典元素的修改
print("dict1[1] = ",dict1[1])
dict1[1]=0
print("dict1[1] = ",dict1[1])
print("dict5['1+7j']= ",dict5["1+7j"])
dict5["1+7j"]=2
print("dict5['1+7j']= ",dict5["1+7j"])
相应输出为
dict1[1] = a
dict1[1] = 0
dict5['1+7j']= 4
dict5['1+7j']= 2
需要指出的是,get方法不能用于修改。即不能使用dict1.get(1)=0
字典元素的删除
print("dict1=",dict1)
del dict1[1]
print("dict1=",dict1)
del dict1
# print("dict1=",dict1)
print("dict6=",dict6)
dict6.pop(1)
print("dict6=",dict6)
dict6.clear()
print("dict6=",dict6)
相应输出为
dict1= {1: 0, 2: 23, 4: (1+5j)}
dict1= {2: 23, 4: (1+5j)}
dict6= {1: {2: 23, 4: (1+5j)}, 2: {'1': 'j', '2': 2}, 3: {}, 4: {'1+2j': 4, '4-5j': 5}, 5: {'1+7j': 2, '2': 5, 1: 'sdfsdf'}}
dict6= {2: {'1': 'j', '2': 2}, 3: {}, 4: {'1+2j': 4, '4-5j': 5}, 5: {'1+7j': 2, '2': 5, 1: 'sdfsdf'}}
dict6= {}
共有四种删除方式
(1)del dictname[key]
(2)dictname.pop[key]
(3)del dictname
(4)dictname.clean()
需要指定的是,del字典后,该字典变量就不存在了,因此,不能再次访问。
字典其它工具方法 print("dict5 length = ", len(dict5)) #字典长度
print("dict5 keys =",dict5.keys()) #字典key集合
print("dict5 values = ",dict5.values()) #字典值集合
print("dict5 items =", dict5.items()) #字典item集合
相应输出为
dict5 length = 3
dict5 keys = dict_keys(['1+7j', '2', 1])
dict5 values = dict_values([2, 5, 'sdfsdf'])
dict5 items = dict_items([('1+7j', 2), ('2', 5), (1, 'sdfsdf')])