Search code examples
pythongammu

Python error when tryint to access list by index - “List indices must be integers, not str”


I have this Python code:

sm.GetSMSStatus() 
sm.GetSMSFolders() 
sms = sm.GetNextSMS(Start = True, Folder=0)
sms = sm.GetNextSMS(Location = sms['Location'], Folder=0)
sms = sm.GetSMS(Location = loc, Folder = 0)

And I'm getting the error:

    Traceback (most recent call last):
  File "sms_teste.py", line 43, in <module>
    sms = sm.GetNextSMS(Location = sms['Location'], Folder=0)
TypeError: list indices must be integers, not str

What I did to try to solve:

First I've been looking for answers to identical problems, however I can not find any that is similar.

According made ​​a print of sms variable to see what it returns and see how is allocated 'Location', and this is the print on:

[{'RejectDuplicates': 0, 'SMSCDateTime': datetime.datetime(2014, 7, 1, 16, 31, 58), 'Class': 1, 'Name': u'', 'InboxFolder': 0, 'Text': u'dsgfzggzdfrg', 'SMSC': {'DefaultNumber': u'', 'Format': 'Text', 'Number': u'+#####', 'Validity': 'Max', 'Location': 0, 'Name': u''}, 'ReplaceMessage': 0, 'Coding': 'Default_No_Compression', 'Number': u'+#####', 'DateTime': None, 'DeliveryStatus': 0, 'State': 'UnSent', 'MessageReference': 0, 'Length': 12, 'Location': 0, 'Memory': 'SM', 'ReplyViaSameSMSC': 0, 'UDH': {'Text': '', 'ID16bit': 0, 'AllParts': 0, 'ID8bit': 0, 'PartNumber': -1, 'Type': 'NoUDH'}, 'Type': 'Submit', 'Folder': 2}]

and I noticed that 'Location' is equal to 0, but your key to getting there is 'Location' But now I'm in a dead end, how do I transform a key string to integer when the variable itself is made ​​with string keys? I am using gammu, so the form are returned as the result of functions is pre-formatted.

Someone can give me a hand?

I hope my information will be useful so that you can understand my question P. S. the phone numbers are on # # # on purpose


Solution

  • What happens is that sms is a list (because of the brackets []). And its only element is a dictionary {}.

    What can you do? You can access to the unique element of that list, which will be a dictionary:

    sms[0]['Location']
    ......
       '-----> dictionary