>>> dict1 = {'a':'1','b':'2','c':'3','d':'4'}
為江陰等地區(qū)用戶提供了全套網(wǎng)頁設(shè)計(jì)制作服務(wù),及江陰網(wǎng)站建設(shè)行業(yè)解決方案。主營(yíng)業(yè)務(wù)為成都網(wǎng)站設(shè)計(jì)、網(wǎng)站建設(shè)、江陰網(wǎng)站設(shè)計(jì),以傳統(tǒng)方式定制建設(shè)網(wǎng)站,并提供域名空間備案等一條龍服務(wù),秉承以專業(yè)、用心的態(tài)度為用戶提供真誠的服務(wù)。我們深信只要達(dá)到每一位用戶的要求,就會(huì)得到認(rèn)可,從而選擇與我們長(zhǎng)期合作。這樣,我們也可以走得更遠(yuǎn)!
>>> print('a的值是:',dict1['a'])
a的值是: 1
>>> dict4 = dict('我' = '快樂', 你 = '傷悲')
SyntaxError: keyword can't be an expression
>>> dict4['你'] = '改變悲傷'
>>> dict4
{'我': '快樂', '你': '改變悲傷'}
>>> dict4['他'] = '多加一個(gè)'
>>> dict4
{'我': '快樂', '你': '改變悲傷', '他': '多加一個(gè)'}
fromkeys(S[,v]) 創(chuàng)建并返回一個(gè)新的字典
>>> dict1 = {}
>>> dict1.fromkeys((1,2,3))
{1: None, 2: None, 3: None}
>>> dict1.fromkeys((1,2,3),'num')
{1: 'num', 2: 'num', 3: 'num'}
>>> dict1.fromkeys((1,3),'數(shù)字') #如果想用fromkeys修改鍵的值,不會(huì)成功會(huì)創(chuàng)建新的字典
{1: '數(shù)字', 3: '數(shù)字'}
訪問字典的方法
keys()
values()
items()
>>> dict2 = {}
>>> dict2 = dict2.fromkeys(range(2),'列子')
>>> dict2
{0: '列子', 1: '列子'}
>>> for eachkey in dict2.keys(): #values為'列子'
print(eachkey)
0
1
>>> for eachitem in dict2.items():
print(eachitem)
(0, '列子')
(1, '列子')
get() 查找方法
>>> dict2 = dict2.fromkeys(range(10),'列子')
>>> dict2
{0: '列子', 1: '列子', 2: '列子', 3: '列子', 4: '列子', 5: '列子', 6: '列子', 7: '列子', 8: '列子', 9: '列子'}
>>> dict2.get(5,'無') #如果有則返回值,如果沒有則返回'無'
'列子'
>>> dict2.get(10,'無')
'無'
>>> 5 in dict2 #成員操作符判定
True
>>> 10 in dict2
False
clean() 清空一個(gè)字典
>>> dict2.fromkeys(range(1),'快樂')
{0: '快樂'}
>>> dict2.clear()
>>> dict2
{}
copy()
>>> a = {1:'one',2:'two',3:'three',4:'four'}
>>> a
{1: 'one', 2: 'two', 3: 'three', 4: 'four'}
>>> b = a.copy()
>>> c = a
>>> b
{1: 'one', 2: 'two', 3: 'three', 4: 'four'}
>>> c
{1: 'one', 2: 'two', 3: 'three', 4: 'four'}
>>>
>>> c[5] = 'five'
>>> c
{1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five'}
>>> a
{1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five'}
>>> b
{1: 'one', 2: 'two', 3: 'three', 4: 'four'}
pop()
popitem() 隨機(jī)彈出
>>> a.pop(2)
'two'
>>> a
{1: 'one', 3: 'three', 4: 'four', 5: 'five'}
>>> a.popitem()
(5, 'five')
>>> a
{1: 'one', 3: 'three', 4: 'four'}
>>> a.setdefault(7,'seven')
'seven'
>>> a
{1: 'one', 3: 'three', 4: 'four', 7: 'seven'}
>>> b = {7:'SEVEN'}
>>> a
{1: 'one', 3: 'three', 4: 'four', 7: 'seven'}
>>> a.update(b)
>>> a
{1: 'one', 3: 'three', 4: 'four', 7: 'SEVEN'}