美文网首页
Python-字典

Python-字典

作者: 浪费不过白头发 | 来源:发表于2017-03-05 16:00 被阅读10次

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浅拷贝&深拷贝&赋值

相关文章

  • 04Python学习之路-字典

    Python-字典 创建字典 如果学过OC 感觉, 一个样 dict函数 转为字典通过键找到值 d["age"] ...

  • 05Python学习之路-流程控制

    Python-字典 创建字典 如果学过OC 感觉, 一个样 dict函数 转为字典通过键找到值 d["age"] ...

  • Python-字典

  • Python-字典

    Python --字典 类似其他的hash,关联数组,key-value,key不可变。 创建字典 方法1:dic...

  • python-字典

    1、字典: 两大特点:无序,键唯一 无序存储,键值对的形式存储数据 键是唯一不可修改的,不能...

  • python-字典

    根据value的不同,字典里面的value可以是字符,数字,列表,字典 ​python学习:《生信宝典py》:Py...

  • Python-字典

    1、空字典的代码是怎样的? {} 2、一个字典包含键‘fow'和值 42,看起来是怎样的? {'fow':42} ...

  • python-字典,元祖

    元祖

  • Python-字典Dictionary

    备注:本文整理学习自:菜鸟教程 一、简介 字典为可变容器模型,可存储任意类型对象 字典中的键值对使用冒号“:”分割...

  • python-字典基础

    # 字典 dict # 初始化 {dict} form_key # dict1 = {} # dict2 = {1...

网友评论

      本文标题:Python-字典

      本文链接:https://www.haomeiwen.com/subject/wucnwttx.html