python基础之字典篇
tips:字典是另一种可变容器模型,且可存储任意类型对象,字典是由键值对构成,键必须是不可迭代对象,值可以为任意对象
一,字典的声明与赋值
#声明一个字典 dict = {} #字典初始化赋值 dict = {"name":"wuxiaoshi","major":"programmer"}
二,字典的查询
#读取字典 dict = {"name":"wuxiaoshi","major":"programmer"} dict['name'] # wuxiaoshi dict['major'] #programmer #循环读取 for key,item in dict.items(): print(item) # 值 wuxiaoshi,programmer print(key) #键 name,major
三,字典的新增
# 字典的添加 dict = {} dict['name'] = 'wuxiaoshi' dict['age'] = 20 print(dict) #{"name":"wuxiaoshi","age":20} #setdefault(key,value) 键无则添加 键有则不变,值无就是None dict = {} dict.setdefault('age',20) dict.setdefault('name':'wuxiaoshi') dict.setdefault('name':'xiaowushi') dict.setdefault('hobbdy') print(dict) # {'age': 20, 'name': 'wuxiaoshi', 'hobbdy': None}
四,字典的删除
#pop(key) 如果key存在,则删除key相应的这个键值对,并返回key对应的value,否则,将会报错 KeyError dict = {"name":"wuxiaoshi","age":20,"hobby":"reading,writting"} print(dict.pop('name')) # wuxiaoshi print(dict) #{'age': 20, 'hobby': 'reading,writting'} print(dict.pop('a')) # KeyError:a #popitem() D.popitem() -> (k, v), remove and return some (key,value) pair as a 2-tuple; but raise KeyError if D is empty. dict = {"name":"wuxiaoshi","age":20,"hobby":"reading,writting"} print(dict.popitem()) # 理论上是随机删除一个,可能会有问题 #del 删除 dict = {"name":"wuxiaoshi","age":20,"hobby":"reading,writting"} del dict['name'] #删除 name的键值对 del dict #删除整个字典,从内存中把空间抹掉 #clear 清空,但是保留内存地址 dict.clear() # {}
五,字典的更新
# 直接更改方法 dict = {"name":"wuxiaoshi","age":20,"hobby":"reading,writting"} dict['name'] = 'xiaowushi' print(dict) #{'name': 'xiaowushi', 'age': 20, 'hobby': 'reading,writting'} #update ''' update(...) method of builtins.dict instance D.update([E, ]**F) -> None. Update D from dict/iterable E and F. If E is present and has a .keys() method, then does: for k in E: D[k] = E[k] If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v In either case, this is followed by: for k in F: D[k] = F[k] 翻译过来就是 有则更新,无则添加 ''' dict1 = {"name":"wuxiaoshi","age":20,"hobby":"reading,writting"} dict2 = {"name":"furao","major":"programmer"} dict1.update(dict2) # {'name': 'furao', 'age': 20, 'hobby': 'reading,writting', 'major': 'programmer'} dict2.update(dict1) #{'name': 'wuxiaoshi', 'major': 'programmer', 'age': 20, 'hobby': 'reading,writting'}
六,字典的内置函数
# get() 通过Key来找值,如果key不存在,可以设置一个默认值 dict = {"name":"furao","major":"programmer"} dict.get("name") # furao dict.get('age',18) # 18 #keys() 获取字典中的key 返回dict_keys dict = {"name":"wuxiaoshi","age":20,"hobby":"reading,writting"} dict.keys() # dict_keys(['name', 'age1', 'hobby']) 如果想返回列表 则list强转 list(dict.keys()) # ['name', 'age', 'hobby'] #values() dict = {"name":"wuxiaoshi","age":20,"hobby":"reading,writting"} dict.values() # ['wuxiaoshi', 20, 'reading,writting'] #items() dict.items() # [('name', 'wuxiaoshi'), ('age1', 20), ('hobby', 'reading,writting')]