关于Python的深复制和浅复制, 字典列表集合可变容器模型, a = b 都是潜复制,当将b[i]修改,则a也被修改,但是若对b重新赋值(及将b指向新的对象), 则a 与b 将不同。而元组字符串不可变容器模型没有copy方法。
a = b.copy()是深拷贝,
copy模块里有copy和deepcopy,copy是浅拷贝,deepcopy是深拷贝,import copy a = copy.copy(b)
a = copy.deepcopy(b)
>>>
a
=
dict
(one
=
1
, two
=
2
, three
=
3
)
>>>
b
=
{
'one'
:
1
,
'two'
:
2
,
'three'
:
3
}
>>>
c
=
dict
(
zip
([
'one'
,
'two'
,
'three'
], [
1
,
2
,
3
]))
>>>
d
=
dict
([(
'two'
,
2
), (
'one'
,
1
), (
'three'
,
3
)])
>>>
e
=
dict
({
'three'
:
3
,
'one'
:
1
,
'two'
:
2
})
>>>
a
==
b
==
c
==
d
==
e
True
字典(dictionary)是Python中另一个非常有用的内置数据类型。
列表是有序的对象结合,字典是无序的对象集合。两者之间的区别在于:字典当中的元素是通过键来存取的,而不是通过偏移存取。
字典是一种映射类型,字典用"{ }"标识,它是一个无序的键(key) : 值(value)对集合。
键(key)必须使用不可变类型。
在同一个字典中,键(key)必须是唯一的。
注意:
- 1、字典是一种映射类型,它的元素是键值对。
- 2、字典的关键字必须为不可变类型,且不能重复。
- 3、创建空字典使用 { }。
(1)字典含的内置函数
- a = {'a':2, 'b':3}
- len(a)输出a 的长度
- str(a)输出字典可打印的字符串标识。"{'a':2, 'b':3} "
- type(variable)返回输入的变量类型,如果变量是字典就返回字典类型
-
-
iter(d)
Return an iterator over the keys of the dictionary. This is a shortcut for
iter(d.keys()).
-
-
d[key] = value
Set
d[key] to
value.
-
-
del d[key]
Remove
d[key] from
d. Raises a KeyError if
key is not in the map.
-
-
key in d
-
Return
True
if
d
has a key
key
, else
False
.
key not in d
Equivalent to
not key in d
.
-
-
clear
(
)
Remove all items from the dictionary.
(2) Python字典包含的内置方法
- dict.clear()
- dict.copy()是深复制
- dict.fromkeys(,)fromkeys(iterable, value=None, /) method of builtins.type instance Returns a new dict with keys from iterable and values equal to value.
- dict.get(key, default = None)返回指定键的值,如果值不在字典中,返回default
-
-
items
(
)
Return a new view of the dictionary’s items (
(key, value) pairs). See the documentation of view objects.
-
-
pop
(
key
[
,
default
]
)
If
key is in the dictionary, remove it and return its value, else return
default. If
default is not given and
key is not in the dictionary, a KeyError is raised.
-
-
popitem
(
)
Remove and return an arbitrary
(key, value) pair from the dictionary.
popitem() is useful to destructively iterate over a dictionary, as often used in set algorithms. If the dictionary is empty, calling popitem()raises a KeyError.
-
-
setdefault
(
key
[
,
default
]
)
If
key is in the dictionary, return its value. If not, insert
key with a value of
default and return
default.
default defaults to
None.
-
-
update
(
[
other
]
)
Update the dictionary with the key/value pairs from
other, overwriting existing keys. Return
None.
update() accepts either another dictionary object or an iterable of key/value pairs (as tuples or other iterables of length two). If keyword arguments are specified, the dictionary is then updated with those key/value pairs:
d.update(red=1, blue=2).
- dict.keys()
-
-
values
(
)
Return a new view of the dictionary’s values. See the documentation of view objects.