字典
定义: D={}. 逗号分隔元素, 元素为key:value对.
info={'name':'PatHoo','age':18,'sex':'male'}
#本质 info=dict({'name':'PatHoo','age':18,'sex':'male'})
1 info={'name':'PatHoo','age':18,'sex':'male'} 2 print(info['age'])
>>> 18 3 info['height']=1.80 4 print(info)
>>> {'name': 'PatHoo', 'age': 18, 'sex': 'male', 'height': 1.8}
5 for key in info: 6 print(key)
>>> name
age
sex
height
#字典的key必须是不可变类型,也称为可hash类型
1 info={(1,2):'a'} 2 print(info[(1,2)])
>>> a
#字典常用的方法(优先掌握)
1 info={'name':'PatHoo','age':18,'sex':'male'} 2 print(info.pop('name'))
>>> PatHoo 3 print(info)
>>> {'age': 18, 'sex': 'male'}
4 print(info.pop('asdfsadfasdfasfasdfasdfasdf',None)) #不存在的键值可以指定报错信息, 默认KeyError
>>> None
1 print(info['name1']) #不存在的键值报错
>>> #KeyError 2 print(info.get('name1')) #不存在的键值默认返回None
>>> None 3 print(info.get('nameasdfasdfasdfasdf','not key')) #可以修改默认返回值
>>> not key
#字典其他的方法
1 info={'name':'PatHoo','age':18,'sex':'male'} 2 print(info.popitem()) #返回(Key, Value)元组
>>> ('sex','male') 3 print(info.popitem()) #字典是无序的
>>> ('name','PatHoo') 4 print(info)
>>> {'age':18}
1 print(info.keys(),type(info.keys()))
>>> dict_keys(['age']) <class 'dict_keys'>
2 print(info.values())
>>> dict_values([18])
1 for key in info.keys(): 2 print(key)
>>> age
1 for val in info.values(): 2 print(val)
>>> 18
1 for key in info: 2 print(key,info[key])
>>> age 18
1 print(info.items())
>>> dict_items([('age', 18)])
2 for key,value in info.items(): # key,value=('age',18) 3 print(key,value)
>>> age 18
1 msg_dic={ 2 'apple':10, 3 'tesla':100000, 4 'mac':3000, 5 'lenovo':30000, 6 'chicken':10, 7 } 8 for key,value in msg_dic.items(): 9 print(key,value)
>>>
apple 10
tesla 100000
mac 3000
lenovo 30000
chicken 10
1 info={'name':'PatHoo','age':18,'sex':'male'} 2 info.clear() 3 print(info)
>>> {}
1 print(info.items())
>>> dict_items([])
2 dic=info.fromkeys(['name','age','sex'],11111111) 3 print(dic)
>>> {'name': 11111111, 'age': 11111111, 'sex': 11111111}
1 dic=info.fromkeys(['name','age','sex'],None) 2 print(dic)
>>> {'name': None, 'age': None, 'sex': None}
1 dic=dict(a=1,b=2,c=3) 2 print(dic)
>>> {'a': 1, 'b': 2, 'c': 3}
1 print(dict([('name', 'PatHoo'), ('age', 18), ('sex', 'male')]))
>>> {'name': 'PatHoo', 'age': 18, 'sex': 'male'}
1 print(info)
>>> {} 2 dic={'a':1,'b':2,'name':'SHUAI'} 3 info.update(dic) 4 print(info)
>>> {'a': 1, 'b': 2, 'name': 'SHUAI'}
1 d={} 2 d['name']='PatHoo' 3 d['age']=18 4 d['sex']='male' 5 d['hobby']=[] 6 d['hobby'].append('play basketball') 7 d['hobby'].append('play football') 8 print(d)
>>> {'name': 'PatHoo', 'age': 18, 'sex': 'male', 'hobby': ['play basketball', 'play football']}
1 d.setdefault('hobby',[]).append('play1') #d['hobby'] 2 d.setdefault('hobby',[]).append('play2') #d['hobby'] 3 d.setdefault('hobby',[]).append('play3') #d['hobby'] 4 print(d)
>>> {'name': 'PatHoo', 'age': 18, 'sex': 'male', 'hobby': ['play basketball', 'play football', 'play1', 'play2', 'play3']}