字典
>>> y={'vookii':'Me','kiki':'notme'}
>>> type(y)
<class 'dict'>
>>> y['vookii']
'Me'
>>> y['civy']='cy'
>>> y
{'vookii': 'Me', 'kiki': 'notme', 'civy': 'cy'}
"6种方法写字典"
>>> a={'vookii': 'Me', 'kiki': 'notme', 'civy': 'cy'}
>>> b=dict(vookii='Me',kiki='notme',civy='cy')
>>> c=dict([('vookii','Me'),('kiki','notme'),('civy','cy')])
>>> d=dict({'vookii':'Me','kiki':'notme','civy':'cy'})
>>> e=dict({'vookii':'Me','kiki':'notme'},civy='cy')
>>> f=dict(zip(['vookii','kiki','civy'],['Me','notme','cy']))
>>> a==b==c==d==e==f
True
增&删
'fromkeys用于强制数组或者初始化数组用'
>>> d=dict.fromkeys('vookii',12)
>>> d
{'v': 12, 'o': 12, 'k': 12, 'i': 12}
>>> d['o']=17
>>> d
{'v': 12, 'o': 17, 'k': 12, 'i': 12}
>>> d['m']=19
>>> d
{'v': 12, 'o': 17, 'k': 12, 'i': 12, 'm': 19}
'删除指令pop'
>>> d.pop('v')
12
>>> d
{'o': 17, 'k': 12, 'i': 12, 'm': 19}
>>> d.pop('a')
Traceback (most recent call last):
File "<pyshell#21>", line 1, in <module>
d.pop('a')
KeyError: 'a'
>>> d.pop('a','none')
'none'
>>> d.popitem()
('m', 19)
>>> d
{'o': 17, 'k': 12, 'i': 12}
>>> del d['i']
>>> d
{'o': 17, 'k': 12}
>>> del d
>>> d
Traceback (most recent call last):
File "<pyshell#28>", line 1, in <module>
d
NameError: name 'd' is not defined
>>> d=dict.fromkeys('vookii',16)
>>> d
{'v': 16, 'o': 16, 'k': 16, 'i': 16}
>>> d.clear()
>>> d
{}
改&查
>>> d=dict.fromkeys('vookii')
>>> d
{'v': None, 'o': None, 'k': None, 'i': None}
>>> d['o']=12
>>> d
{'v': None, 'o': 12, 'k': None, 'i': None}
>>> d.update({'v':15,'k':17})
>>> d
{'v': 15, 'o': 12, 'k': 17, 'i': None}
>>> d.update(i='20',o='21')
>>> d
{'v': 15, 'o': '21', 'k': 17, 'i': '20'}
'查'
>>> d.get('v')
15
>>> d.get('l','这里没有')
'这里没有'
>>> d.setdefault('o','ok')
'21'
>>> d.setdefault('m','ok')
'ok'
>>> d
{'v': 15, 'o': '21', 'k': 17, 'i': '20', 'm': 'ok'}
视图对象
d={'v': 15, 'o': '21', 'k': 17, 'i': '20', 'm': 'ok'}
>>> keys=d.keys()
>>> values=d.values()
>>> items=d.items()
>>> keys
dict_keys(['v', 'o', 'k', 'i', 'm'])
>>> values
dict_values([15, '21', 17, '20', 'ok'])
>>> items
dict_items([('v', 15), ('o', '21'), ('k', 17), ('i', '20'), ('m', 'ok')])
>>> d.pop('o')
'21'
>>> d
{'v': 15, 'k': 17, 'i': '20', 'm': 'ok'}
>>> keys
dict_keys(['v', 'k', 'i', 'm'])
>>> values
dict_values([15, 17, '20', 'ok'])
>>> items
dict_items([('v', 15), ('k', 17), ('i', '20'), ('m', 'ok')])
嵌套
'嵌套'
>>> d={'vookii':{'Chinese':80,'Math':90,"English":85},'kiki':{'Chinese':70,'Math':60,'English':95}}
>>> d['vookii']['Chinese']
80
>>> d['kiki']['Math']
60
>>> f={'vookii':[80,90,85],'kiki':[70,60,95]}
>>> f['kiki'][1]
60
字典推导式
>>> d={'v':70,'a':101,'c':123,'h':90,'k':89}
>>> b={m:n for n,m in d.items()}
>>> b
{70: 'v', 101: 'a', 123: 'c', 90: 'h', 89: 'k'}
>>> d={x:ord(x) for x in 'vookii'}
>>> d
{'v': 118, 'o': 111, 'k': 107, 'i': 105}
>>> d={x:y for x in [1,3,5] for y in [2,4,6]}
>>> d
{1: 6, 3: 6, 5: 6}