fromkeys
接受
1 一个可以迭代的对象
2 值 value
通过迭代对象的key找到对应值,然后把接受到的值赋值给对应的key的value,但是不是修改value,因为它是生成一个新的dict
mydict = {"a":2,"B":3,"V":5}
dict_gen = {key:value for key,value in mydict.items()}
cpone = dict.fromkeys(dict_gen, {2,3,4})
print(cpone)
{'B': {2, 3, 4}, 'V': {2, 3, 4}, 'a': {2, 3, 4}}
cpone = dict.fromkeys("V", {"D":7})
print(cpone)
{'V': {'D': 7}}
深拷贝和浅拷贝
cpone = {'B': {"F":4}, 'V': {"D": 4}, 'a': {"b":4}}
cptwo = cpone.copy()
cptwo["V"]["D"] = 2
#修改第二层的key是属于第一层的操作
cptwo["B"] = {"a":1}
print(cpone)
print(cptwo)
{'B': {'F': 4}, 'V': {'D': 2}, 'a': {'b': 4}}
{'B': {'a': 1}, 'V': {'D': 2}, 'a': {'b': 4}}
mydict = {"a":2,"B":3,"V":5}
dict_gen = {key:value for key,value in mydict.items()}
cpone = dict_gen.copy()
cpone["a"] = 4
print(dict_gen)
print(cpone)
{'B': 3, 'V': 5, 'a': 2}
{'B': 3, 'V': 5, 'a': 4}
浅拷贝只把第一层的key:value给复制过来,第二次的key:value只是复制一个指针(指针指向原来的key value),所以修改第二层的value时,会把原来的修改了;修改第二层的key是属于第一层的操作
# 深度拷贝
cpone = {'B': {"F":4}, 'V': {"D": 4}, 'a': {"b":4}}
import copy
cptwo = copy.deepcopy(cpone)
cptwo["V"]["D"] = 2
cptwo["B"] = {"a":1}
print(cpone)
print(cptwo)
{'B': {'F': 4}, 'V': {'D': 4}, 'a': {'b': 4}}
{'B': {'a': 1}, 'V': {'D': 2}, 'a': {'b': 4}}
网友评论