python - Assign a dictionary value to a variable where key == list[element] -


c = d[s[0]] c new variable, d dictionary, , s list.

what i'm attempting assign value of key same first element list c. know key in dictionary, , first element of list same key. how assign value of key variable? code wrote gives me out of index error.

however, code:

a = s[0] c = d[a] 

works. why doesn't first attempt work? python 2.7 on windows

i have no idea why not working you. maybe list not populated after all. should work -

>>> d={'world':'hunger'} >>> s=['world'] >>> d[s[0]] 'hunger' >>> c = d[s[0]] >>> c 'hunger' >>>  

also python dictionaries have nifty feature called has_key. checks if key present in dict or not. use prevent keyerror exceptions... consider using prevent untoward crashes.


Comments

Popular posts from this blog

monitor web browser programmatically in Android? -

Shrink a YouTube video to responsive width -

wpf - PdfWriter.GetInstance throws System.NullReferenceException -