1. 程式人生 > >字典 dict

字典 dict

python

In [43]: a = dict(k1=‘v1‘,k2=‘v2‘)

In [44]: type(a)
Out[44]: dict

In [45]: a
Out[45]: {‘k1‘: ‘v1‘, ‘k2‘: ‘v2‘}


#這個方法和a這個字典沒關系呀,沒看懂。實際上就是生成新的字典。
In [47]: new_a = a.fromkeys([‘k‘],‘v‘)

In [48]: new_a
Out[48]: {‘k‘: ‘v‘}

In [49]: new_a = a.fromkeys([‘k‘,‘w‘],‘v‘)

In [50]: new_a
Out[50]: {‘k‘: ‘v‘, ‘w‘: ‘v‘}


#get方法。輸入key,輸出對應的value
In [54]: a.get(‘k1‘)
Out[54]: ‘v1‘


In [57]: a.get(‘k3‘,‘vv‘)    #如果輸入一個不存在的key,就返回NONE,或者可以指定返回的值
Out[57]: ‘vv‘


In [59]: a.keys()
Out[59]: dict_keys([‘k1‘, ‘k2‘])

In [60]: type(a.keys())
Out[60]: dict_keys

In [61]: a.values()
Out[61]: dict_values([‘v1‘, ‘v2‘])

In [62]: a.items()
Out[62]: dict_items([(‘k1‘, ‘v1‘), (‘k2‘, ‘v2‘)])

#用for循環輸出key,輸出的是字符串
In [65]: for k in a.keys():
    ...:     print(k)
    ...:     print(type(k))
    ...:       
k1
<class ‘str‘>
k2
<class ‘str‘>

#輸出的是元組
In [66]: for k in a.items():
    ...:     print(k)
    ...:     print(type(k))
    ...:     
(‘k1‘, ‘v1‘)
<class ‘tuple‘>
(‘k2‘, ‘v2‘)
<class ‘tuple‘>


In [68]: for k,v in a.items():
    ...:     print(k,v)
    ...:     
k1 v1
k2 v2

#pop方法需要輸入參數,指定刪除一個key的鍵值對。不寫參數會報錯
In [71]: a.pop(‘k1‘)
Out[71]: ‘v1‘

In [72]: a
Out[72]: {‘k2‘: ‘v2‘}

#popitem不需要輸入參數,隨機pop一個。
In [76]: a
Out[76]: {‘k1‘: ‘v1‘, ‘k2‘: ‘v2‘}

In [77]: a.popitem()
Out[77]: (‘k2‘, ‘v2‘)

In [78]: a
Out[78]: {‘k1‘: ‘v1‘}

#添加一個鍵值對
In [80]: a[‘k3‘]=‘v3‘

In [81]: a
Out[81]: {‘k1‘: ‘v1‘, ‘k3‘: ‘v3‘}

#update也是添加
In [93]: a
Out[93]: {‘k1‘: ‘v1‘, ‘k3‘: ‘v3‘, ‘k4‘: ‘v4‘, ‘k5‘: ‘v5‘}

In [94]: a.update({‘k2‘:‘v2‘})

In [95]: a
Out[95]: {‘k1‘: ‘v1‘, ‘k2‘: ‘v2‘, ‘k3‘: ‘v3‘, ‘k4‘: ‘v4‘, ‘k5‘: ‘v5‘}


字典 dict