For in loop over dict gives TypeError: string indices must be integers

前端 未结 2 589
栀梦
栀梦 2021-01-25 23:02

I have a dict with 11 items in it, here\'s a scree shot from Spyder variable explorer:

def buildDF(result_set):
    master_dm = []
    for p in result_s         


        
2条回答
  •  失恋的感觉
    2021-01-25 23:57

    A similar question can be found here: Iterating over dictionaries using 'for' loops

    From what I can gather you sessions1 is a dictionary containing other dictionaries, so to iterate over the items as it would appear you would like to, you would need to use .items() method on the dictionary i.e:

    def buildDF(result_set):
        master_dm = []
        for key, p in result_set.items():
            rows = p['reports']
            master_dm.append(rows)
        return(master_dm)
    

    What you are doing at the moment is just iterating over the list of keys which are strings. This means the line p['reports'] in your original code is trying to access the 'reports' element of whatever key it is looking at at the time. This cannot be done as strings can be only indexed with integers - hence the error.

提交回复
热议问题