how to get dictionary value in python from dynamic key -


from xlrd import open_workbook  book = open_workbook('trial.xls') sheet=book.sheet_by_index(0)  name_email={}  i=0 row_index in range(sheet.nrows):     if name_email.has_key(sheet.cell(row_index,i).value):          name_email[str(sheet.cell(row_index,i).value.strip())]=sheet.cell(row_index,i+1).value,)     else:                       abc = str(sheet.cell(row_index,i).value.strip())         print repr(abc)         print '"{0}"'.format(repr(abc))         # print name_email[abc]         name_email[str(sheet.cell(row_index,i).value.strip())]=sheet.cell(row_index,i+1).value i+=1             print name_email.keys() print name_email 

the out put : 'manoj' "'manoj'" 'dibyendu' "'dibyendu'" 'sourav' "'sourav'" ['dibyendu', 'sourav', 'manoj'] {'dibyendu': (u'd.b@gmail.com',), 'sourav': (u's.b@gmail.com',), 'manoj': (u'm.c@gmail.com',)}

but still cant access print name_email[abc] throwing error print name_email[abc] keyerror: 'manoj'

problem lies not in variable used index (which fine, , works 1 expect), in if condition.

your code

if name_email.has_key(sheet.cell(row_index,i).value):     name_email[str(sheet.cell(row_index,i).value)]=(sheet.cell(row_index,i+1).value,) else:     #print name_email[str(sheet.cell(row_index,i).value)]      abc= str(sheet.cell(row_index,i).value)     print name_email[abc] 

tries print name_email[abc] if , if name_mail does not contain abc key (as in "else:" sstatement. seems wanted opposite - print when has key, , add when not, right? rearrange if condition.

now like

if x.has_key(y):     x[y] = 1 else:     print x[y] 

while should be

if x.has_key(y):     print x[y] else:     x[y] = 1 

Comments

Popular posts from this blog

html - How to style widget with post count different than without post count -

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

javascript - storing input from prompt in array and displaying the array -