深入python的set和dict

dict ABC继承

dict 属于mapping 类型
例:
from collections.abc import Mapping,MutableMapping
dict1 = {}
print(isinstance(dict1, MutableMapping))
深入python的set和dict_第1张图片
dict 常用方法
clear
清除dict
a = {“zs”:{“company”:“imoc”},
“ls”:{“company”:“aussco”}}
a.clear()
print(a)

深入python的set和dict_第2张图片
copy
a = {“zs”:{“company”:“imoc”},
“ls”:{“company”:“aussco”}}

new_dict = a.copy()
new_dict[“zs”][“company”] = “ax”
new_dict[“ls”][“company”] = “ay”

print(a)
print(new_dict)

copy 返回㳀拷贝
a ,new_dict 的值都改变了
深入python的set和dict_第3张图片
注意:
如果要深拷贝的话,要import copy

import copy
a = {“zs”:{“company”:“imoc”},
“ls”:{“company”:“aussco”}}
new_dict = copy.deepcopy(a)
new_dict[“zs”][“company”] = “ax”
print(a)
print(new_dict)

深入python的set和dict_第4张图片
fromkey
组合成dict
例:
new_list = [“ls”, “ww”]
new_dict = dict.fromkeys(new_list, {“company”: “imoc11”})

print(new_dict)

深入python的set和dict_第5张图片
get
当dict 的key 不存在时显示默认值
深入python的set和dict_第6张图片
dict 查找 的性能远远大于list
在list 中,随着list数据的增大,查找 时间会增大
dict 中查找元素不会随着dict的增大而增大
1, dict 的key 或者set的值 都必须 是可以hash的
不可变对象都是可以hash的。 str ,fronzenset,tuple
自已实现的类 hash
2 dict 的内存花销大,但是查询 速度快.自定义的对象或python 内部的对象都是dict包装的
3,dict 的存储顺序和元素添加有关
4 添加数据有可能改变已有数据的顺序

你可能感兴趣的:(Python,高级编程,python,开发语言,pytorch)