Search code examples
pythondictionarykeyerror

Dictionary returns none in spite of key existing in it


I am loading my dictionary with this in a loop at the beginning of my program. It contains the below values.

{3456: ['TATAMOTORS'], 13404: ['SUNTV'], 3718: ['VOLTAS'], 3499: ['TATASTEEL'], 
5900: ['AXISBANK'], 2885: ['RELIANCE'], 15083: ['ADANIPORTS'], 11287: ['UPL']}

As and when I get streaming data, I want to know what is the stock. For egs. if I pass 3718 I should get 'VOLTAS'. The above dictionary is never changed.

My code is as below. Stream_data is json. And token is fetched correctly

token=stream_data['response']['data']['sym'].replace('_NSE','').strip()
print(token)
print(imp.dictoftokens)
stock = imp.dictoftokens.get(token)

What am I doing wrong? I ried it in console and manually passsed a token and it worked correctly.


Solution

  • Looks like your token object is of type str but your keys are of type int:

    Change the type of token to int and it should work as expected:

    token=int(stream_data['response']['data']['sym'].replace('_NSE','').strip())