您好,登錄后才能下訂單哦!
dict
?
key-value鍵值對的數(shù)據(jù)的集合;
可變的;
無序的;
key不重復(fù),key用來作唯一標(biāo)識,key要為hashable(不可變類型),key的要求和set的元素要求一致;
k,v一起稱為item,d.popitem()彈出的二元組也稱item;
d.items(),在python3中叫dictionary view,如for i in d.items();
?
dict定義、初始化:
d = dict()
d = {}
dict(*kwargs),使用name=value對初始化一個字典;
dict(iterable,**kwargs),使用可迭代對象和name=value對構(gòu)造字典,不過可迭代對象的元素必須是一個二元結(jié)構(gòu);
dict(mapping,**kwargs),使用一個字典構(gòu)造另一個字典;
類方法,dict.fromkeys(iterable,value),如d=dict.fromkeys(range(5),0),0為缺省值;
?
例:
In [1]: d=dict(((1,'a'),(2,'b')))
In [2]: d
Out[2]: {1: 'a', 2: 'b'}
In [3]: d=dict(([1,'a'],[2,'b']))
In [4]: d
Out[4]: {1: 'a', 2: 'b'}
In [5]: d=dict(a=5,b=6,z=[1,2,3])
In [6]: d
Out[6]: {'a': 5, 'b': 6, 'z': [1, 2, 3]}
In [7]: d=dict(a=5,b=6,1=2)?? #1=2有歧義,此處即變量名=value,是非法的標(biāo)識符
? File "<ipython-input-7-8a208196f03e>", line 1
??? d=dict(a=5,b=6,1=2)????????????????? ^
SyntaxError: keyword can't be an expression
In [8]: d={'a':10,'b':20,'c':None,'d':[1,2,3]}
In [9]: d
Out[9]: {'a': 10, 'b': 20, 'c': None, 'd': [1, 2, 3]}
In [10]: d=dict.fromkeys(range(5))?? #value未定義為None
In [11]: d
Out[11]: {0: None, 1: None, 2: None, 3: None, 4: None}
In [12]: d=dict.fromkeys(range(5),0)
In [13]: d
Out[13]: {0: 0, 1: 0, 2: 0, 3: 0, 4: 0}
In [14]: l1=list(range(5))
In [15]: e = enumerate(l1)?? #返回可迭代對象
In [16]: e
Out[16]: <enumerate at 0x7f634c2c4678>
In [17]: for i in e:
??? ...:???? print(i)?? #返回二元組
??? ...:????
(0, 0)
(1, 1)
(2, 2)
(3, 3)
(4, 4)
In [19]: e=enumerate(l1)
In [20]: d=dict(e)
In [21]: d
Out[21]: {0: 0, 1: 1, 2: 2, 3: 3, 4: 4}
In [22]: d={('a',1)} ??#{}里是單個對象,此例為二元組,該類型為set;
In [23]: d
Out[23]: {('a', 1)}
In [24]: type(d)
Out[24]: set
In [25]: d=dict((('a',1),))?? #dict()里要是iterable object,注意逗號,單個二元組不是可迭代對象
In [26]: d
Out[26]: {'a': 1}
In [27]: d=dict(('a',1),)
---------------------------------------------------------------------------
ValueError??????????????????????????????? Traceback (most recent call last)
<ipython-input-27-671890814fce> in <module>()
----> 1 d=dict(('a',1),)
ValueError: dictionary update sequence element #0 has length 1; 2 is required
In [28]: d=dict((('a',1)))
---------------------------------------------------------------------------
ValueError??????????????????????????????? Traceback (most recent call last)
<ipython-input-28-927d7fa29131> in <module>()
----> 1 d=dict((('a',1)))
ValueError: dictionary update sequence element #0 has length 1; 2 is required
In [30]: d=dict.fromkeys(range(1,5),(1,))?? #(1,)為value的缺省值
In [31]: d
Out[31]: {1: (1,), 2: (1,), 3: (1,), 4: (1,)}
In [32]: d=dict.fromkeys(range(1,5),[1,2])
In [33]: d
Out[33]: {1: [1, 2], 2: [1, 2], 3: [1, 2], 4: [1, 2]}
In [34]: d[4].append(3)?? #注意引用類型,會全部變
In [35]: d
Out[35]: {1: [1, 2, 3], 2: [1, 2, 3], 3: [1, 2, 3], 4: [1, 2, 3]}
?
dict元素的訪問:
d[key],返回key對應(yīng)的value,key不存在拋KeyError異常;
get(key[,default]),返回key對應(yīng)的value,key不存在返回缺省值,如果沒有設(shè)置缺省值就返回None;
setdefault(key[,default]),返回key對應(yīng)的value,key不存在添加kv時,value為default,并返回default,如果default沒有設(shè)置,缺省為None;當(dāng)不確定某key的value是否存在用setdefault();
?
例:
In [47]: d=dict(([(1,3,4),(2,5,8,9)],))?? #(1,3,4)為key,(2,5,8,9)為value
In [48]: d
Out[48]: {(1, 3, 4): (2, 5, 8, 9)}
In [49]: d[(1,3,4)]
Out[49]: (2, 5, 8, 9)
In [50]: f=d.get((1,3,4))
In [51]: f
Out[51]: (2, 5, 8, 9)
In [52]: f=d.get((1,4,3))
In [53]: f
In [54]: type(f)
Out[54]: NoneType
In [55]: d.get(1,50)
Out[55]: 50
In [56]: d.get((1,3,4),50)
Out[56]: (2, 5, 8, 9)
In [57]: d.setdefault(3)
In [58]: d
Out[58]: {(1, 3, 4): (2, 5, 8, 9), 3: None}
In [66]: f=d.setdefault(4,400)
In [67]: f
Out[67]: 400
In [68]: f=d.setdefault(4,401)
In [69]: f
Out[69]: 400
?
dict增加修改:
d[key]=value,將key對應(yīng)的value改為value;key不存在,添加新的kv對;
update([other])-->None,使用另一個字典的kv時更新本字典,key不存在就添加,key存在覆蓋已存在的key對應(yīng)的value,就地修改;
?
例:
In [36]: d={}
In [37]: type(d)
Out[37]: dict
In [38]: d.update(red=1)
In [39]: d
Out[39]: {'red': 1}
In [40]: d.update((('red',2),))
In [41]: d
Out[41]: {'red': 2}
In [42]: d.update({'red':3})
In [43]: d
Out[43]: {'red': 3}
In [75]: del d
In [76]: d=dict(a=1,b=2)
In [77]: d
Out[77]: {'a': 1, 'b': 2}
In [78]: d['c']=3?? #沒有則創(chuàng)建
In [79]: d
Out[79]: {'a': 1, 'b': 2, 'c': 3}
In [80]: d['c']=8?? #有則修改
In [81]: d
Out[81]: {'a': 1, 'b': 2, 'c': 8}
In [82]: d2=dict(red=3)
In [83]: d2
Out[83]: {'red': 3}
In [84]: d.update(d2,red=8)?? #關(guān)鍵字參數(shù),red=1要放到最后
In [85]: d
Out[85]: {'a': 1, 'b': 2, 'c': 8, 'red': 8}
?
dict刪除:
pop(key[,default]),key存在,移除它,并返回它的value;key不存在,返回給定的default;default未設(shè)置,key不存在時拋KeyError異常;
popitem(),移除并返回一個任意的kv對,字典為empty拋KeyError異常,k,v一起稱為item,popitem()彈出的二元組也稱item;
clear(),清空字典;
注意,不能用for loop一邊迭代一邊刪元素,用while可以對比長度;
del語句;
?
例:
In [86]: d=dict.fromkeys(range(5),[1,2,3])
In [87]: d
Out[87]: {0: [1, 2, 3], 1: [1, 2, 3], 2: [1, 2, 3], 3: [1, 2, 3], 4: [1, 2, 3]}
In [88]: f=d.pop(4)
In [89]: f
Out[89]: [1, 2, 3]
In [90]: d
Out[90]: {0: [1, 2, 3], 1: [1, 2, 3], 2: [1, 2, 3], 3: [1, 2, 3]}
In [91]: f.append(4)?? #注意引用類型
In [92]: d
Out[92]: {0: [1, 2, 3, 4], 1: [1, 2, 3, 4], 2: [1, 2, 3, 4], 3: [1, 2, 3, 4]}
In [93]: d.popitem()
Out[93]: (0, [1, 2, 3, 4])
In [94]: d.popitem()
Out[94]: (1, [1, 2, 3, 4])
In [95]: d.popitem()
Out[95]: (2, [1, 2, 3, 4])
In [96]: d.popitem()
Out[96]: (3, [1, 2, 3, 4])
In [97]: d.popitem()
---------------------------------------------------------------------------
KeyError????????????????????????????????? Traceback (most recent call last)
<ipython-input-97-83c64cff336b> in <module>()
----> 1 d.popitem()
KeyError: 'popitem(): dictionary is empty'
?
字典遍歷:
遍歷key:
for k in d:
???????? print(k)
for k in d.keys():
???????? print(k)
?
遍歷value:
for k in d:
???????? print(d[k])
for k in d.keys():
???????? print(d.get(k))
for v in d.values():
???????? print(v)
?
遍歷item,kv對:
for item in d.items():
???????? print(item)?? #返回(k,v)的二元組
for k,v in d.items():
???????? print(k,v)
?
總結(jié):
python3中,d.keys(),d.values(),d.items()方法返回一個類似生成器的可迭代對象,不會把函數(shù)的返回結(jié)果復(fù)制到內(nèi)存中;
python2中,d.keys(),d.values(),d.items()會返回一個新的列表,占據(jù)新的內(nèi)存空間,所以python2建議使用d.iterkeys(),d.itervalues(),d.iteritems()版本,返回一個迭代器而不是一個copy;
?
for k,_ in d.items():?? #解構(gòu)
???????? print(k)
?
defaultdict:
collections.defaultdict([default_factory[,...]])
default_factory,缺省是None,它提供一個初始化函數(shù),當(dāng)key不存在的時候,會調(diào)用這個工廠函數(shù)來生成key對應(yīng)的value;
?
例:
from collections import defaultdict
d1 = {}
d2 = defaultdict(list)?? #l1=list(),高階函數(shù)
?
for k in 'abcde':
??? for v in range(5):
??????? if k not in d1.keys():
??????????? d1[k] = []
??????? d1[k].append(v)
print(d1)
?
for k in 'mnopq':
??? for v in range(3):
??????? d2[k].append(v)
print(d2)
?
OrderedDict,有序字典:
可記錄元素插入的順序(按加入的順序放),打印時也是按這個順序輸出打?。ú皇?/span>hash值排序的結(jié)果);
3.6版本的python dict按加入順序記錄了key,是按記錄key插入的順序;
collections.OrderedDict([items])
key并不是按照加入的順序排列,可使用OrderedDict記錄順序;
?
例:
from collections import OrderedDict
import random
?
d = {'banana':3,'apple':4,'pear':1,'orange':2}
print(d)
?
keys = list(d.keys())
?
random.shuffle(keys)
print(keys)
?
od = OrderedDict()
for k in keys:
??? od[k] = d[k]?? #往od字典里添kv對
print(od,od.keys())
?
?
?
用戶輸入一個數(shù)字,打印每一位數(shù)字及其重復(fù)的次數(shù)?
例:
import random
?
nums = [random.randint(0,9) for _ in range(5)]?? #[chr(random.randint(48,57)) for _ in range(5)]
print(nums)
nums_dict = {}
?
for i in nums:
??? nums_dict[i] = nums_dict.get(i,0) + 1
print(nums_dict)
?
例:
import random
?
words = [random.randint(0,9) for _ in range(10)]
print(words)
words_count = {}
?
for k,v in zip(words,(1,)*len(words)):
??? words_count[k] = words_count.get(k,0) + 1
lst = sorted(words_count.items(),key=lambda x:x[1],reverse=True)
print(lst)
?
for i in range(3):
??? print(str(lst[i]).strip("()"))
?
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。