Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/355.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 为什么在为使用dict.fromkeys()和大括号初始化的dict赋值时会有差异?_Python_Python 2.7_Dictionary - Fatal编程技术网

Python 为什么在为使用dict.fromkeys()和大括号初始化的dict赋值时会有差异?

Python 为什么在为使用dict.fromkeys()和大括号初始化的dict赋值时会有差异?,python,python-2.7,dictionary,Python,Python 2.7,Dictionary,这是一个例子, my_keys=['hi','hello'] d=dict.fromkeys(my_keys,[]) print d d['hello'].append([1,]) print d['hello'] print d['hi'] d={'hi': [], 'hello': []} print d d['hello'].append([1,]) print d['hello'] print d['hi'] 输出: {'hi': [], 'hello': []} [[1]] [[1

这是一个例子,

my_keys=['hi','hello']
d=dict.fromkeys(my_keys,[])
print d
d['hello'].append([1,])
print d['hello']
print d['hi']

d={'hi': [], 'hello': []}
print d
d['hello'].append([1,])
print d['hello']
print d['hi']
输出:

{'hi': [], 'hello': []}
[[1]]
[[1]]
{'hi': [], 'hello': []}
[[1]]
[]
通过输出,可以看到当一个键的值被修改时,即
d['hello'].append([1,])
如果dict是用
dict.fromkeys()初始化的,则更改键'hi'的值。

classmethod
fromkeys(seq[,value])

使用seq中的键和设置为value的值创建一个新字典

为什么将值赋给使用
dict.fromkeys()
和大括号初始化的dict时会有差异?

dict.fromkeys()
不会复制传入的值,因此您只有一个列表对象。您的
{…}
dict literal创建两个独立的列表

请记住,在Python中,容器(如列表或字典)中包含的属性和对象只是对堆上对象的引用。可以轻松创建对同一对象的多个引用
dict.fromkeys()
只需获取传入的引用,并将其用于所有值。因此
d
中的所有值都指向同一个列表对象:

>>> my_keys = ['hi', 'hello']
>>> d = dict.fromkeys(my_keys)
>>> d['hi'] is d['hello']
True
>>> id(d['hi']), id(d['hello'])
(4508307448, 4508307448)
使用dict理解从需要为值生成单独对象的键列表创建字典:

{k: [] for k in my_keys}
在dict理解中,为
for
循环的每次迭代计算值表达式,因此反复执行
[]
表达式以生成单独的列表对象:

>>> d = {k: [] for k in my_keys}
>>> d['hi'] is d['hello']
False
>>> id(d['hi']), id(d['hello'])
(4514233544, 4514233672)