[英]Unexpected output when appending dict to list
I have written a small API in Python 2.7 that retrieves data from google analytics and sends it to my own website. 我在Python 2.7中编写了一个小API,它从谷歌分析中检索数据并将其发送到我自己的网站。
This is the input 这是输入
{'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 append this to a 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 row with united states 12 times. 它只与美国重复最后一行12次。 I have tried everything but I am getting crazy.
我尝试了一切,但我变得疯狂。 Anybody got a clue?
有人知道吗?
Kind regards. 亲切的问候。
Because the code is using the same dictionary in the loop and updating the dictinoary, and append the same dictionary into the list. 因为代码在循环中使用相同的字典并更新dictinoary,并将相同的字典附加到列表中。
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.