This is a test version of Biostars. For the public version, visit https://www.biostars.org.
Python: How To Get Keys In A Dictionary To Point To Duplicates Rather Than The Same Object

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

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.

2 answers

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

Thank you so much!

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.

Log in to answer this question.