Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Appending a dictionary to a list in a loop

I am trying to take a dictionary and append it to a list. The dictionary then changes values and then is appended again in a loop. It seems that every time I do this, all the dictionaries in the list change their values to match the one that was just appended.

For example:

>>> dict = {} >>> list = [] >>> for x in range(0,100): ...     dict[1] = x ...     list.append(dict) ...  >>> print list 

I would assume the result would be [{1:1}, {1:2}, {1:3}... {1:98}, {1:99}] but instead I got:

[{1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}, {1: 99}] 
like image 941
Acoop Avatar asked May 18 '14 16:05

Acoop


People also ask

Can you append a dictionary to a list?

Appending a dictionary to a list with the same key and different values. Using append() method. Using copy() method to list using append() method. Using deepcopy() method to list using append() method.

How do you append to a list in loop?

You can append a list in for loop, Use the list append() method to append elements to a list while iterating over the given list.

Can you do a for loop for dictionary?

You can loop through a dictionary by using a for loop. When looping through a dictionary, the return value are the keys of the dictionary, but there are methods to return the values as well.

How do you append a dictionary?

Appending element(s) to a dictionary To append an element to an existing dictionary, you have to use the dictionary name followed by square brackets with the key name and assign a value to it.


1 Answers

You need to append a copy, otherwise you are just adding references to the same dictionary over and over again:

yourlist.append(yourdict.copy()) 

I used yourdict and yourlist instead of dict and list; you don't want to mask the built-in types.

like image 179
Martijn Pieters Avatar answered Oct 16 '22 02:10

Martijn Pieters