from collections.abc import Mapping,MutableMapping from collections.abc import __all__ # dict 屬於Mapping類型 a = {} print(isinstance(a,MutableMapping))
a = { "liming1":{"company":"tencent1"}, "liming2":{"company":"tencent2"}, } # clear """ D.clear() -> None. Remove all items from D. """ # a.clear() #copy 淺拷貝 """ D.copy() -> a shallow copy of D """ new_dict = a.copy() new_dict['liming1']['company'] = 'tencent3' print(a) print(new_dict) ########### {'liming1': {'company': 'tencent3'}, 'liming2': {'company': 'tencent2'}} {'liming1': {'company': 'tencent3'}, 'liming2': {'company': 'tencent2'}}
# fromkeys new_list = ['liming1','liming2'] new_dict = dict.fromkeys(new_list,{'company':'tencent'}) print(new_dict)
# update new_dict.update({'lisa':{"company":"tencent2"}}) new_dict.update({'liming2':{"company":"tencent2"}}) new_dict.update(jenny={'company':'beijing'}) new_dict.update([('jenny',{'company':'shanghai'})]) print(new_dict)
__missing__ 很重要
from collections import defaultdict import collections s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)] d = collections.defaultdict(list) for k, v in s: d[k].append(v) print(list(d.items())) s = 'mississippi' d = defaultdict(int) for k in s: d[k] += 1 print(list(d.items()))#set 不可變集合 fronzenset 無序 不重複
剛開始也講了frozenset是不可變的,若是修改是報錯的,那到底有什麼用處呢
應用場景:通常dict 的key 是不變的,咱們就能夠用
那咱們用代碼證實下,set不會報錯,frozenset 會報錯.app
s = {'a','b'} s.add('c') print(s) f = frozenset('abcd') # 能夠做爲dict的key print(f) # 向set添加數據 another_set = set('fgh') s.update(another_set) print(s)
# 先看方法描述吧 ( Return the difference of two or more sets as a new set.)
# 用例子加深印象。
a=set("abc") print(a.difference("bcd")) print(a)
a=set("abc") b=set("bcd") print(a-b) #對a進行去重 print(a | b) #並集 print(a & b) #交集 # {'a'} # {'c', 'a', 'd', 'b'} # {'c', 'b'}