更改一个dict值会更改所有值 [英] Changing One dict value changes all values

查看:116
本文介绍了更改一个dict值会更改所有值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Python词典中看到了一些异常行为:

I am seeing some unusual behavior in Python Dictionary:

import numpy as np
td =[np.Inf, 2, 3]
a = {}
# First initialize contents of dictionary to a list of values
for k in range(10):
    a[k] = td

#now I want to access the contents to modify them based on certain criteria 
for k in range(10):
    c = a[k]
    c[0] = k
    a[k] = c

据此,我希望每个字典键值的列表的每个第一项都基于(c [0] = k)进行更改,但是,最后我得到的是字典的所有值都已更新到k的最后一个值:如

From this I would expect each first item of the list for each dictionary key value to be changed based on (c[0] = k), however, what I get at the end is that ALL values of the dictionary are updated to the last value of k: as in

{0: [9, 2, 3], 1: [9, 2, 3], 2: [9, 2, 3], 3: [9, 2, 3], 
 4: [9, 2, 3], 5: [9, 2, 3], 6: [9, 2, 3], 7: [9, 2, 3], 
 8: [9, 2, 3], 9: [9, 2, 3]}

我错过了什么,还是词典定义有问题? 我可以用不同的方法来解决此问题,以使我的代码运行,但是我对字典类为何会以这种方式运行很感兴趣.

Am I missing something, or there is something wrong in the dictionary definition? I can work around this in a different way for my code to run, but I am interested as to why the dictionary class would behave this way.

推荐答案

因为每个键都获得相同的列表....要对该列表进行浅表复制,请使用以下语法:

Because each key gets the same list... To make a shallow copy of the list, use the following syntax:

for k in range(10):
    a[k] = td[:] 

演示:

>>> d = {}
>>> el = [1, 2, 3]
>>> d[0] = el
>>> d[1] = el
>>> map(id, d.values())
[28358416, 28358416]

这篇关于更改一个dict值会更改所有值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆