字典

 

 

 

 

>>> d = {'china':'bei','usa':'noy','fra':'par'}
>>> d['china']
'bei'
>>> de = {};type(de) #type(x) 返回x 的类型 
<class 'dict'>

 

 

 

>>> del d['usa']
>>> d
{'china': 'bei', 'fra': 'par'}
>>> 'china ' in d
False
>>> 'china' in d
True
>>> d.keys()
dict_keys(['china', 'fra'])
>>> d.values()
dict_values(['bei', 'par'])
>>> d.items()
dict_items([('china', 'bei'), ('fra', 'par')])

 loop

d = {'person': 2, 'cat': 4, 'spider': 8}
for anminal in d:#默认d.keys()
    legs = d[anminal]
    print('A %s has %d legs' % (anminal,legs))

A person has 2 legs
A cat has 4 legs
A spider has 8 legs


d = {'person': 2, 'cat': 4, 'spider': 8}
for anminal, legs in d.items():
    print('A %s has %d legs' % (anminal,legs))


A person has 2 legs
A cat has 4 legs
A spider has 8 legs

 

word2Ind_ans = {'All': 0, "All's": 1, 'END': 2, 'START': 3, 'ends': 4, 'glitters': 5, 'gold': 6, "isn't": 7, 'that': 8, 'well': 9}
for w1 in word2Ind_ans.keys():
    print(w1,word2Ind_ans[w1])
All 0
All's 1
END 2
START 3
ends 4
glitters 5
gold 6
isn't 7
that 8
well 9

 

 

>>> d
{'china': 'bei', 'fra': 'par'}
>>> d.get('china','dvv')
'bei'>>> d.get('c','dvv')
'dvv'
>>> d.pop('china','dvv')#同时删除
'bei'
>>> d
{'fra': 'par'}
>>> d.popitem()#同时删除
('fra', 'par')
>>> d
{}
>>> d.clear()
>>> d = {'adv':'dv','d':'dd'}
>>> len(d)
2

 

posted on 2019-11-18 10:12  cltt  阅读(116)  评论(0编辑  收藏  举报

导航