Unexpected output when adding dict to list

I wrote a small API in Python 2.7 that pulls data from Google Analytics and sends it to my own site.

This is the entrance

{'country': '(not set)', 'visits': '1'}
{'country': 'Belgium', 'visits': '9'}
{'country': 'Brazil', 'visits': '2'}
{'country': 'Germany', 'visits': '2'}
{'country': 'Mexico', 'visits': '2'}
{'country': 'Netherlands', 'visits': '38'}
{'country': 'Philippines', 'visits': '1'}
{'country': 'Portugal', 'visits': '1'}
{'country': 'Spain', 'visits': '1'}
{'country': 'Thailand', 'visits': '1'}
{'country': 'United Kingdom', 'visits': '1'}
{'country': 'United States', 'visits': '1'}

      

When I add this to the list with the following code:

new_dict = {}
new_list = []
for row in query:
    for count, attribute in enumerate(list_of_dim_met):    
        new_dict.update({
            attribute.replace('ga:',''): row[count].encode('ascii','ignore')
            })
    new_list.append(new_dict)
print new_list

      

it only repeats the last line with the combined states 12 times. I've tried everything, but I'm going crazy. Does anyone understand the key?

Sincerely.

+3


source to share


1 answer


Because the code uses the same dictionary in a loop and updates the dictinoary and adds the same dictionary to the list.

Make a new dictionary in a loop instead of using the same dictionary.



new_list = []
for row in query:
    for count, attribute in enumerate(list_of_dim_met):    
        new_dict = {
            attribute.replace('ga:',''): row[count].encode('ascii','ignore')
        }
    new_list.append(new_dict)

      

+1


source







All Articles