Python字典中的键值未更新
我有一个奇怪的问题,因为我试图生成字典列表以将它们作为参数传递给函数. 手动"设计输入看起来像这样:
I have a weird problem, as I am trying to generate a list of dictionaries to pass them as a parameter to a function. Designing the input "by hand" looks like this:
params = [
# Amazon
{
'q': "AMZN",
'x': "NASDAQ",
},
{
'q': "PIH",
'x': "NASDAQ",
},
{
'q': "AIR",
'x': "NYSE",
},
{
'q': "FCO",
'x': "NYSEAMERICAN",
},
{
'q': "7201",
'x': "TYO",
}
].
我尝试通过包含以下代码的txt文件从清单文件(每行一个)的txt文件生成类似的字典列表:
I have tried to generate a similar list of dictionaries from a txt file containing a list of tickers (one per line) with the following code:
info = {}
params = []
with open('Test_Tickers.txt') as f:
for line in f:
info['q'] = line.rstrip()
info['x'] = "NYSE"
params.append(info)
print(info)
令人沮丧的是,虽然print(info)返回正确的字典
The frustrating part is that while the print(info) returns the correct dictionaries
{'q': 'ABB', 'x': 'NYSE'}
{'q': 'ABBV', 'x': 'NYSE'}
{'q': 'ABC', 'x': 'NYSE'}
{'q': 'ABEV', 'x': 'NYSE'}
...
{'q': 'IJS', 'x': 'NYSE'}
参数看起来像这样:
[{'q': 'IJS', 'x': 'NYSE'}, {'q': 'IJS', 'x': 'NYSE'}, {'q': 'IJS', 'x': 'NYSE'}, {'q': 'IJS', 'x': 'NYSE'}, {'q': 'IJS', 'x': 'NYSE'}, {'q': 'IJS', 'x': 'NYSE'}, {'q': 'IJS', 'x': 'NYSE'}, {'q': 'IJS', 'x': 'NYSE'}, ... ]
我该如何使代码正确,以便词典包含所有行情收录器,而不仅是最后一个收录器?
How can I corrent the code so that the dictionaries contain all the tickers and not only the last one?
params = []
with open('Test_Tickers.txt') as f:
for line in f:
info = {}
info['q'] = line.rstrip()
info['x'] = "NYSE"
params.append(info)
print(info)
我会工作
您仅更新list中的一个dict对象,
要创建多个对象,您必须在循环内定义info = {}
you were updating only one dict object in list ,
to make multiple object you have to define info = {}
inside the loop