Python字典中的键值未更新 [英] Value of a key in a Python dictinary is not updating

查看:127
本文介绍了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

这篇关于Python字典中的键值未更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆