Python: How To Get Keys In A Dictionary To Point To Duplicates Rather Than The Same Object
2
1
Entering edit mode
12.6 years ago
Mark ▴ 10

alt text

The picture is the best way to explain my problem, but I'm trying to populate a dictionary object in python, such that each key in the dictionary has a value of a list. Currently, all keys point to the same list. This is not what I want. Instead, I want each key to be associated with an independent copy of that list. I don't want to change the list in dict[1] and have that change also occur in dict[2].

If there is a better object for this kind of task that a dict, I would love to hear that advise as well.

I tried using a list (of lists), but this gave me the same error (which surprised me).

Thanks! A bit of a noob! Sorry!

This is some code that might be helpful:

samples={} for x in range (1,653): samples[x]=list

so, I want the same list to be the value of every key in the dictionary, but when I type

sample[3].append('Hello'), I don't want sample[4] to also contain the appended 'Hello'.

python • 6.3k views
ADD COMMENT
0
Entering edit mode

To clarify, my keys are integers. It's the values that they're pointing to (a list, specifically) that I'm having a problem with.

ADD REPLY
0
Entering edit mode

cross-posted on stats.stackexchange.com: http://stats.stackexchange.com/questions/16629

ADD REPLY
4
Entering edit mode
12.6 years ago

In Python, you can use copy or deepcopy (from module copy) to pass a copy of an object rather than the object itself.

import copy

a = [1,2,3]
b = a
b[2] = 99 # now a[2] = 99 too

a = [1,2,3]
b = copy.copy(a)
b[2] = 99 # now a[2] is unchanged

To sum up, you could pass your lists to the dictionary as:

dictionary[key] = copy.copy(value_list) # or use copy.deepcopy

For nested structures, use copy.deepcopy instead of copy.copy so that you create a copy of all the nested levels.

Cheers

ADD COMMENT
0
Entering edit mode

Thank you so much!

ADD REPLY
3
Entering edit mode
12.6 years ago
brentp 24k

Here's an ipython session that illuminates why you're seeing what you're seeing.

In [1]: d = {}

In [2]: alist = range(4)

In [3]: d['bad'] = alist

In [4]: d['ok'] = alist[:]

In [5]: alist.append("EXTRA")

In [6]: d
Out[6]: {'bad': [0, 1, 2, 3, 'EXTRA'], 'ok': [0, 1, 2, 3]}

Note that alist[:] makes a copy so it is not affected by the subsequent append. You can also use copy.copy() for more rigor as suggested by @Eric.

ADD COMMENT

Login before adding your answer.

Traffic: 3031 users visited in the last hour
Help About
FAQ
Access RSS
API
Stats

Use of this site constitutes acceptance of our User Agreement and Privacy Policy.

Powered by the version 2.3.6