Python-字典

Python --字典

类似其他的hash,关联数组,key-value,key不可变。

创建字典

方法1:dict1 = {1:'one',2:'two',3,"three"}

dict1 = {} //空字典

方法2: dict(mapping) -> new dictionary initialized from a mapping object's  (key, value) pairs

t1 = ((1,'one'),(2,'two'))   #元组不可变类型

dict2 = dict(t1) #工厂函数

dict2 = dict()

访问字典

通过key访问value

one = dict1[1]  # 1 是 key

方法

1.D.clear()   与 D = {} 的区别?   #D为字典

>>> dict1 = {1:'one',2:"two",3:"three"}

>>> dict2 = dict1  #赋值是将dict2这个引用指向dict1指向的字典

>>> hex(id(dict1))

'0x25149b56f48'

>>> hex(id(dict2))

'0x25149b56f48'

>>> dict1 = {}

>>> dict1

{}

>>> dict2    

{1: 'one', 2: 'two', 3: 'three'}

>>> hex(id(dict1)) # 创建了一个新的空字典

'0x25149bc5ec8'

>>> hex(id(dict2))

'0x25149b56f48'

>>> dict1 = dict2

>>> dict1.clear() #与dict1的引用指向相同的都置空

>>> dict1

{}

>>> dict2

{}

>>> hex(id(dict1))

'0x25149b56f48'

>>> hex(id(dict2))

'0x25149b56f48'

2.D.copy()   

>>> dict1 = {1:'one',2:'two'}

>>> dict2 = dict1.copy() #浅拷贝

>>> hex(id(dict1))

'0x25149bc6748'

>>> hex(id(dict2))

'0x25149bc5ec8'

浅拷贝(shallow copy)  VS 深拷贝(deep copy) 在copy

compound objects (objects that contain other objects, like lists or class instances) 时有区别

>>> import copy

>>> a = [1,2,3]

>>> b = [4,5,6]

>>> c = [a,b]

#普通的赋值

>>> d = c

>>> print(id(c) == id(d))

True

>>> print(id(c[0]) == id(d[0])

)

True

#浅拷贝

sd = copy.copy(c)

>>> print(id(sd) == id(c))

False

>>> print(id(sd[0]) == id(c[0])) #引用的拷贝

True

#深拷贝

>>> dd = copy.deepcopy(c)

>>> print(id(dd)==id(c))

False

>>> print(id(dd[0]) == id(c[0])) #新建的对象

False


参考链接

1.shallow copy & deep copy

2浅拷贝&深拷贝&赋值

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 一、字典基本操作 基本语法:dict = {'ob1':'computer', 'ob2':'mouse', 'o...
    古佛青灯度流年阅读 7,488评论 0 1
  • 字典dict python内置了字典,使用键-值(key-value)存储。键必须是唯一的,但值则不必。特点是速度...
    光刃小刀阅读 6,824评论 0 0
  • 1. 字典的一些知识点 字典特性可变、可存储任意类型对象、无序 字典的生成?直接用dict 字典的排序?sorte...
    海螺上的斑点阅读 3,093评论 0 0
  • 1、创建和使用字典 >>> phonebook = {'Alice': '2342', 'Beth': '9102...
    VB过得VB阅读 1,885评论 0 1
  • 本篇将介绍Python里面的字典,更多内容请参考:Python学习指南 Python是什么? Python内置了字...
    小七奇奇阅读 5,266评论 0 5