#python 基礎系列07-字典集合 #引入sys庫 import sys import copy if __name__ == '__main__': a,b,c =1,2,3 #字段的訪問效率速度要優於集合跟元組,字典是無序的,是可變的 mydict = {1:'a111',2:'bccc'} print(type(mydict)) print(mydict[1],mydict[2]) #創建字典 方式一 dict1 = dict((['1','2'],['aa','bb'])) print(dict1) #{1: 2, 'aa': 'bb'} # 創建字典 方式二 dict2 = dict.fromkeys([1,2,3,4],'xxxx') dict3 = dict.fromkeys('abcd','xxxx') print(dict2)#{1: 'xxxx', 2: 'xxxx', 3: 'xxxx', 4: 'xxxx'} print(dict3) #{'a': 'xxxx', 'b': 'xxxx', 'c': 'xxxx', 'd': 'xxxx'} #字典獲取參數值 print(dict1.keys()) #dict_keys([1, 'aa']) print(dict1.values()) #dict_values([2, 'bb']) print(dict1['1'],dict1['aa']) #循環 for var in dict1: print(var) #判斷key是否存在 ,不能判斷value值 print('1' in dict1) #刪除值 del mydict[1] print(mydict) #pop 函數刪除值 並保持值 rs = mydict.pop(2) print(mydict) # {} print(rs) #bccc #清空字典 mydict.clear() #集合set 分爲可變跟不可變集合 ,集合是去重的類似set,集合是亂序的 myset = {'a','b','c','d','d'} myset2 = set([1,2,3,4]) print(myset) #創建不可變集合 myset_no = frozenset([1,2,34,5,6]) #循環訪問值 for i in myset: print(i) #更新集合 #不可變集合不能更新 myset.add(('1','2')) print(myset) myset.update(('112aa','hhhh')) #{'b', '112aa', 'hhhh', ('1', '2'), 'a', 'c', 'd'} print(myset) #判斷是否在 print('a' in myset) #刪除集合 #myset.remove() #del myset #判斷交集和子集 myset < myset #前者是否是後者的子集 myset > myset #前者是否是後者的超集 #集合跟集合聯合 交集 差補 對稱差分 myset | myset myset & myset myset - myset myset ^ myset