注:最后有面试挑战,看看自己掌握了吗
键值对dict—哈希表构成(无序)
不能直接修改键,
本质是哈希表,键不能重复!
值可以是python支持的任何对象
增
法1
if '__main__' == __name__: d={1:123,2:569} d[3] = 123 print(d)
法2
setdefault
函数,默认为None
if '__main__' == __name__: d={1:123,2:569} d.setdefault(3,'129z') print(d)
查
法1
d={1:123,2:569} d.setdefault(3,'129z') print(d[2])
法2
if '__main__' == __name__: d = {1: 123, 2: 569} d.setdefault('zzz', '129z') print(d.get('zzz'))
改
法1
法2-也可用来新增
if '__main__' == __name__: d = {1: 123, 2: 569} d.setdefault('zzz', '129z') d.update({'zzz':'111'}) print(d.get('zzz'))
删
法1
del
函数
from Box_model import * import math import sys if '__main__' == __name__: d = {1: 123, 2: 569} d.setdefault('zzz', '129z') d.update({'zzz':'111'}) print(d.get('zzz')) del(d[1]) print(d)
法2
if '__main__' == __name__: d = {1: 123, 2: 569} p = d.pop(1) print(p)
法3
随机返回一个键值对元组,并且删除对应元素
if '__main__' == __name__: d = {1: 123, 2: 569} p = d.popitem() print(p)
if '__main__' == __name__: d = {1: 123, 2: 569} k,v = d.popitem() print(v)
遍历
遍历所有键值对
item()
–以元组返回所有字典元素
if '__main__' == __name__: d = {1: 123, 2: 569} for item in d.items(): print(item)
if '__main__' == __name__: d = {1: 123, 2: 569} print(d.items())//<class 'builtin_function_or_method'>
遍历所有键
if '__main__' == __name__: d = {1: 123, 2: 569} for i in d: print(i)
if '__main__' == __name__: d = {1: 123, 2: 569} for i in d.keys(): print(i)
遍历所有值
if '__main__' == __name__: d = {1: 123, 2: 569} for i in d.values(): print(i)
if '__main__' == __name__: d = {1: 123, 2: 569} for i in d: print(d[i])
其他方法
in
if ‘item’ in d
clear
copy
if '__main__' == __name__: d = {1: 123, 2: 569} d2 = d.copy() print(id(d)) print(id(d2)) 2757616058112 2757616058304
if '__main__' == __name__: d = {1: 123, 2: 569} d2 = d print(id(d)) print(id(d2)) 2818139340544 2818139340544
fromkeys-指定相关键 生成 空值字典
if '__main__' == __name__: d = {}.fromkeys('1','zzz') print(d) {'1': 'zzz'}
🌸I could be bounded in a nutshell and count myself a king of infinite space.
特别鸣谢:木芯工作室 、Ivan from Russia