Python Textfile – Assign Numbers to words in dic

I have a txt file I’m pulling from sec.gov with the following code

import requests

cik = requests.get('https://www.sec.gov/include/ticker.txt').text
mylist = cik.split()

output from the site looks like this:

aapl    320193
msft    789019
amzn    1018724
goog    1652044
fb      1326801
tcehy   1293451

And I splitted to have each ticker & number seperated as string like this: ['aapl', '320193', 'msft', '789019', 'amzn', '1018724', 'goog', '1652044', 'fb', '1326801']

How can I combine each Ticker with the following number?

Answer

One way to map the provided output to a dictionary through parsing is as follows:

Get the text output into response:

>>> import requests
>>> resp = requests.get("https://www.sec.gov/include/ticker.txt").text

Now, if you check the first line you will see that it is aap1t320193n. This is useful information that helps in understanding that a split by n first then by t can be performed and then append directly to a dictionary:

>>> combinations = resp.split("n")
>>> dict_test = {}
>>> for element in combinations:
# Here, element.split("t")[0] will be aap1 and element.split("t")[1] will be 320193
    dict_test[element.split("t")[0]] = element.split("t")[1]

Finally, the first 5 output is shown below since the dictionary itself is too big:

>>> for idx, key in enumerate(dict_test.keys()):
    if idx == 5:
        break
    print("Key: {} and its Value: {}".format(key, dict_test[key]))

Output:

Key: aapl and its Value: 320193
Key: msft and its Value: 789019
Key: amzn and its Value: 1018724
Key: goog and its Value: 1652044
Key: fb and its Value: 1326801