I wrote a code in python which looks like:
maplist=[{}]*11
mylist=[0]*11
maplist[0]['this']=1
print maplist
When I print maplist the output is :
[{'this': 1}, {'this': 1}, {'this': 1}, {'this': 1}, {'this': 1}, {'this': 1}, {'this': 1}, {'this': 1}, {'this': 1}, {'this': 1}, {'this': 1}]
Expected is:
[{'this': 1}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}]
rather than only the first element of the list should have this key in the map. What is causing this problem?
-
It's amazing how often we get a subtle variation on the same question... in addition to marking things as duplicates, I'm starting to feel like we need to have a way to create a per-tag FAQ.Karl Knechtel– Karl Knechtel2012年01月26日 10:17:32 +00:00Commented Jan 26, 2012 at 10:17
2 Answers 2
When you do the following:
maplist=[{}]*11
you end up with eleven references to the same dictionary. This means that when you modify one dictionary, they all appear to change.
To fix, replace that line with:
maplist=[{} for in xrange(11)]
Note that, since 0 is a scalar, the next line is fine as it is:
mylist=[0]*11
2 Comments
The problem is when you type
maplist=[{}]*11
You're creating a list of 11 references to the same dict. Only one dictionary gets created.
To create 11 separate dictionaries you can do something like this:
>>> maplist = [{} for i in range(11)]
>>> maplist[0]['this'] = 1
>>> maplist
[{'this': 1}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}]