1.数据类型的分类
按可变和不可变分
可变(可哈希)
list 、dict 、set
不可变(不可哈希)
str 、bool 、int 、tuple
2.字典的初识
字典是容器型数据:dict
格式:以{}括起来,以键值对形式存储的容器型数据类型。
dict1= {
'老师' :
{
'name' : '吕小树' , 'age' : 25 , 'sex' : '男' } ,
'18秋法学本科班' :
[ '王小二' , '李铁柱' , '李黑碳' ]
}
键:唯一的,必须是不可变的数据类型:int、str(常用),bool、tuple(几乎不用)
值:可重复的,可以是任意数据类型,对象。
Python各版本中字典的区别:
字典3.5 版本之前(包括3.5 )是无序的。
字典3 . 6x会按照初次建立字典的顺序排列,但学术上不认为是有序的。
字典3 . 7x以后都是有序的。
字典的优点:查询速度非常快,存储关联性的数据
字典的缺点:以空间换时间。
3.字典的使用(增删改查)
字典的创建方式
dict1 = dict ( ( ( 'one' , 1 ) , ( 'two' , 2 ) , ( 'three' , 3 ) ) )
print ( dict1)
>> > {
'one' : 1 , 'two' : 2 , 'three' : 3 }
ict1 = dict ( one= 1 , two= 2 , three= 3 )
print ( dict1)
>> > {
'one' : 1 , 'two' : 2 , 'three' : 3 }
dict1 = dict ( {
'one' : 1 , 'two' : 2 , 'three' : 3 } )
print ( dict1)
>> > {
'one' : 1 , 'two' : 2 , 'three' : 3 }
dict1 = {
'one' : 1 , 'two' : 2 , 'three' : 3 }
增
dict1[ 'name' ] = '吕小树'
dict1[ 'one' ] = 'one'
dict1. setdefault( 'sex' , '男' )
dict1. setdefault( 'name' , '吕布' )
>> > {
'one' : 1 , 'two' : 2 , 'three' : 3 , 'name' : '吕小树' , 'sex' : '男' }
删
dict.pop()方法 (***):删除键值对。删除指定键,返回该键对应的值。
dict1 = {
'one' : 1 , 'two' : 2 , 'three' : 3 }
print ( dict1. pop( 'age' , '没有此键' ) )
>> > {
'one' : 1 , 'two' : 2 , 'three' : 3 }
dict.clear()方法:清空该字典,并非删除这个字典。
dict.del()方法:删除指定键值对,但没有返回值,如果字典中无该键,程序报错。
dict1 = {
'one' : 1 , 'two' : 2 , 'three' : 3 }
del dict1[ 'one' ]
>> > {
'two' : 2 , 'three' : 3 }
改
dict['键名'] = 值
dict.updata()方法
查
dict1 = {
'one' : 1 , 'two' : 2 , 'three' : 3 , 'name' : '吕小树' , 'sex' : '男' }
print ( dict1[ 'name' ] )
>> > 吕小树
dict.get()方法 ★★★:如果没有要查询的键名,将返回’None’,或指定内容。
dict1 = {
'one' : 1 , 'two' : 2 , 'three' : 3 , 'name' : '吕小树' , 'sex' : '男' }
print ( dict1. get( 'age' ) )
>> > None
print ( dict1. get( 'age' , '没有此键' ) )
>> > 没有此键
dict.keys()方法:返回值是一个列表,多用于跟for循环使用。
dict1 = {
'one' : 1 , 'two' : 2 , 'three' : 3 , 'name' : '吕小树' , 'sex' : '男' }
print ( dict1. keys( ) )
dict . values( ) 方法:返回值是一个列表,多用于跟for 循环使用。
dict1 = {
'one' : 1 , 'two' : 2 , 'three' : 3 , 'name' : '吕小树' , 'sex' : '男' }
for value in dict1. values( ) :
print ( value)
dict.items() 方法:返回每个键值对(元组),多用于for循环结合遍历整个字典的每个键值对。
dict1 = {
'one' : 1 , 'two' : 2 , 'three' : 3 , 'name' : '吕小树' , 'sex' : '男' }
for key, value in dict1. items( ) :
print ( key, value)
>> > one 1
two 2
three 3
name 吕小树
sex 男
4.字典的嵌套
dict1 = {
'name' : '李小伟' ,
'age' : 26 ,
'wife' : [ {
'name' : '小章' , 'age' : 22 } , ] ,
'children' : {
'girl' : '小苹果' , 'boy' : '小圈' }
}
print ( dict1. get( 'name' ) )
print ( dict1[ 'wife' ] [ 0 ] )
print ( dict1[ 'wife' ] [ 0 ] [ 'name' ] )
print ( dict1[ 'children' ] [ 'boy' ] )
>> >
李小伟
{
'name' : '小章' , 'age' : 22 }
小章
小圈
5.综合运用:字符串转字典
有字符串"k: 1|k1:2|k2:3 |k3 :4" 处理成字典 {‘k’:1,‘k1’:2…}
msg = 'k: 1|k1:2|k2:3 |k3 :4| K4: 58'
dict1 = {
}
list1 = msg. split( '|' )
for i in list1:
key, value = i. split( ':' )
dict1. setdefault( key. strip( ) , int ( value. strip( ) ) )
print ( dict1)
>> > {
'k' : 1 , 'k1' : 2 , 'k2' : 3 , 'k3' : 4 , 'K4' : 58 }
图片分享