标签:cli day src one hid 不可变类 可变 update eve
字典查找速度快,基于哈希索引
字典的key只能是不可变类型
不可变:str,int,bool,tuple
可变类型:list,dict,set
不可变类型
dic = { ‘k1‘:‘v1‘, 2:‘v1‘ False:‘v1‘ (11,22,33):‘v1‘, } print(dic)#{‘k1‘: ‘v1‘, 2: ‘v1‘, False: ‘v1‘, (11, 22, 33): ‘v1‘}
可变类型
dic = { ‘k1‘:‘v1‘, 2:‘v1‘, False:‘v1‘, [11,22,33]:‘v1‘, } print(dic)#TypeError:ynhashable type:‘list‘ 不可哈希
data = [11,22,33,44] dic1 = { ‘k1‘: ‘v1‘, ‘k2‘: data } dic2 = { ‘k1‘: ‘v1‘, ‘k2‘: data } data.append(666) print(dic1) print(dic2)
dic1 = { ‘k1‘: ‘v1‘, ‘k2‘: [11,22,33,44] } dic2 = dic1.copy() print(dic1,dic2) dic1[‘k2‘].append(666) print(dic1,dic2) dic1 = { ‘k1‘: ‘v1‘, ‘k2‘: [11,22,33,44] } import copy dic2 = copy.deepcopy(dic1) print(dic1,dic2) dic1[‘k2‘].append(666) print(dic1,dic2)
dic = {‘k1‘:‘v1‘,‘k2‘:‘v2‘} v = dic.pop(‘k23‘,‘默认值‘) print(dic) print(v)
dic = {‘k1‘:‘v1‘,‘k2‘:‘v2‘} v1,v2 = dic.popitem() print(dic) print(v1,v2)
# dic = {‘k1‘:‘v1‘,‘k2‘:‘v2‘} # 添加 # dic.setdefault(‘k2‘,‘999‘) # print(dic) # 设置:添加,修改 # dic[‘k2‘] = 999
dic = {‘k1‘:‘v1‘,‘k2‘:‘v2‘} # dict类的一个对象 dic.update({‘k4‘:‘v4‘,‘k2‘:‘v5‘}) print(dic)
val = dict.fromkeys([‘k1‘,‘k2‘,‘k3‘],666) print(val) val[‘k1‘] = 999 val = dict.fromkeys([‘k1‘,‘k2‘,‘k3‘],[]) val[‘k1‘].append(678) val[‘k2‘].append(999) print(val) val = dict.fromkeys([‘k1‘,‘k2‘,‘k3‘],[]) val[‘k1‘].append(666) val[‘k1‘] = [1,2,3] print(val) v = [11,22,33] v.append(55) # 修改内部 v = [1,2,3] v1 = "strasdf" v = "sfsfs"
标签:cli day src one hid 不可变类 可变 update eve
原文地址:http://www.cnblogs.com/ngya/p/7625610.html