-1

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",
    }
].

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)

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'}

the params looks like this:

[{'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?

user3612816
  • 325
  • 2
  • 11

1 Answers1

1
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)

I will work

you were updating only one dict object in list , to make multiple object you have to define info = {} inside the loop

Ravi Bhushan
  • 942
  • 2
  • 11
  • 19
  • 2
    It will, but a code dump with no explanation is not very helpful in understanding the issue. – Mad Physicist Jun 01 '18 at 02:08
  • you were updating only one dict object in list , to make multiple object you have to define `info = {}` inside the loop – Ravi Bhushan Jun 01 '18 at 02:13
  • the answer is 100 % correct – Ravi Bhushan Jun 01 '18 at 02:14
  • 1
    I admitted as much up front. The issue is not with your code but with the fact that this site is intended to be a place for OP and future readers to gain understanding. A code dump may patch OP's problem in the short term, but won't help anyone understand anything if they don't already. Thanks for making the update. Downvote removed. – Mad Physicist Jun 01 '18 at 02:16