gdogg371
gdogg371

Reputation: 4132

Key error when using dictionary definitions

I am using the following code which is producing a key error (1, 2) and I'm not sure why:

import concurrent.futures
import urllib.request
import json


myurls2 = {}
for x in range(1, 15):
    for y in range(1, 87):

        strvar1 = "%s" % (x)
        strvar2 = "%s" % (y)

        with open("C:\\Python33\\NASDAQ Stock Strings\\NASDAQ_Config_File_{}_{}.txt".format(x,y),"r") as f:
            myurls2[x,y] = f.read().replace('\n', '')            
            #print("myurls_" + str(strvar1) + "_" + str(strvar2) + "=", myurls2[x,y])
            #print(myurls2[x,y])

            URLS = [myurls2[1,1],myurls2[1,2],myurls2[1,3],myurls2[1,4],myurls2[1,5]]

When the line '#print(myurls2[x,y])' is uncommented you can see that the dictionary definition is correctly iterating through the text files that generate the dictionary values, but the dictionary keys cannot then be referenced.

Upvotes: 0

Views: 69

Answers (1)

jrennie
jrennie

Reputation: 1957

In the first pass through, where x=1 and y=1, you have only defined myurls[1,1]. In other words, you have yet to define myurls[1,2] (or any of the other myurls).

Are you sure that URLS should not be defined after the for x and for y loops are complete?

As @inspectorG4dget notes, it might be that URLS needs de-denting out of scope of the for loops.

Upvotes: 2

Related Questions