字典
字典的定义
1 ''' 2 字典定义: 3 字典是一种数据的集合,由键值对组成的数据集合,字典中的键不能重复 4 字典中的键必须是不可变的数据类型,常用的主要是:字符串,整形.... 5 ''' 6 7 vardict = {'a':1,'b':2,'c':3} 8 # list(d) 9 # 返回字典 d 中使用的所有键的列表。 10 11 print(list(vardict)) 12 13 # len(d) 14 # 返回字典 d 中的项数。 15 16 print(len(vardict)) 17 18 # d[key] 19 # 返回 d 中以 key 为键的项。 如果映射中不存在 key 则会引发 KeyError。 20 21 vardict = dict(name='zhansan',sex='man') 22 23 print(vardict) 24 25 # 数据类型的转换 dict(二级容器) 列表或元组 26 vardict = dict((('a',1),('b',2))) 27 28 print(vardict) 29 30 var1 = [1,2,3,4] 31 var2 = ['a','b','c','d'] 32 res = zip(var1,var2) 33 vardict = dict(res) 34 print(vardict) 35 36 # 添加元素 如果键重复则会被覆盖 37 vardict['aa'] = 'AA' 38 vardict['bb'] = 'AA' 39 print(vardict) 40 41 print(vardict.keys()) 42 43 print(vardict.values()) 44 45 print(vardict.items()) 46 47 for k,v in vardict.items(): 48 print(k,v)
字典的相关函数
1 # . 字典的相关函数 2 3 4 # iter(d) 返回以字典的键为元素的迭代器 5 vardict = {'a':1,'b':2,'c':3} 6 7 # res = iter(vardict) 8 # print(list(res)) 9 10 # dict.pop(key) 通过key从字典中弹出键值 key不存在时报错 11 # res = vardict.pop('a') 12 # print(res) 13 # print(vardict) 14 15 # dict.popitem(key) 返回最后一个键值对 没有时报错 16 # res = vardict.popitem() 17 # print(res) 18 # print(vardict) 19 20 # dict.get(key,不存在时返回的值) 通过key获取value 没有时默认返回None 不报错 21 22 res = vardict.get('a',"不存在") 23 print(res) 24 25 # dict.update() 更新字典 如果key存在则更新 否则添加新的键值对 26 vardict.update(t=1) 27 print(vardict) 28 29 # dict.setdefault(key[,value]) 查找key,存在返回值,不存在添加key=value并返回值 30 res = vardict.setdefault('a',5) 31 print(res) 32 print(vardict)
字典推导式
# 字典推导式 # 把字典中的键值对位置交换,vardict = {'a':1,'b':2,'c':3} vardict = {'a':1,'b':2,'c':3} # newdict = {} # for k,v in vardict.items(): # newdict[v] = k # # print(newdict) # 使用字典推导式完成 # newdict = {v:k for k,v in vardict.items()} # print(newdict) # 注意 以下推导式返回的为集合 # newset = {v for k,v in vardict.items()} # print(newset,type(newset)) # newset = {k for k,v in vardict.items()} # print(newset) # 把字典中的是偶数的值,保留下来,并且交换键值对的位置 newdict = {v:k for k,v in vardict.items() if v%2==0} print(newdict)