Hossein
Hossein

Reputation: 41831

Problem with dictionary key in Python

For some project I have to make a dictionary in which the keys are urls,among which I have this url:

http://www.microsoft.com/isapi/redir.dll?prd=windows&sbp=mediaplayer&ar=Media&sba=Guide&pver=6.2

the url is too long to fit in here I guess in one single line. I can build a dictionary without any errors this url is also a key. but for some reason when I want to extract the values associated to this key(url). I cannot, I get and error "error key:...." Does someone know what is wrong with this url? Are dictionary keys sensitive to some stuff? thanks

below is the code:

def initialize_sumWTP_table(cursor):
cursor.execute( ''' SELECT url,tagsCount
                     FROM sumWTP''')
rows = cursor.fetchall ()
for url,tagsCount in rows:
    sumWTP[url] = tagsCount

Upvotes: 0

Views: 363

Answers (4)

Hossein
Hossein

Reputation: 41831

The problem was a bug in my code. I added some exception handling to solve the problem.The data was right, but I have forgotten to do exception handling in these cases. example:

def getWPT(url,tag):
try:
    row = MemoryInitializer.wtp[url][tag]
except KeyError:
    row = 0
#print row
return row

Upvotes: 1

wisty
wisty

Reputation: 7061

It is almost inconceivable that the dictionary is "losing" your key. I would guess that there is some small change in the string (case, or how the query string is ordered) that results in the same effective URL, but with a slightly different string.

If this is the case, find a way to "normalize" the URL.

Upvotes: 1

Pierce
Pierce

Reputation: 346

It's hard to tell based on the code fragment offered. It looks like you are initializing the dictionary. You need to create the sumWTP dictionary first, something like: sumWTP = {}. Then statements like sumWTP[url] = tagcount should work.

Upvotes: 0

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798566

The reason for getting a key error when accessing a dict is that the key does not exist. Verify that the key you think exists, and that you're using the correct string.

Upvotes: 0

Related Questions