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

戏子无情 提交于 2020-01-30 11:29:04

问题


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_set:
        rows = p['reports']
        master_dm.append(rows)
    return(master_dm)

sessions1DF = buildDF(sessions1)
TypeError: string indices must be integers

When I view sessions1 I can see that it's a dict with the 11 items per the screen above. Double clicking on one of the items shows the reports inside each item:

Why am I getting this error and how can I build a new list with the 11 reports lists which are nested under each item in result_set?


回答1:


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.




回答2:


When iterating over the dictionary try calling the dict.items() method:

sessions1 = {10000:'val1',100000:'val2',2000:'val3',3000:'val4',4000:'val5',5000:'val6',6000:'val7',7000:'val8',8000:'val9',9000:'val10',10000:'val11'}
def buildDF(result_set):
    master_dm = []
    for k,v in result_set.items():
        master_dm.append(v)
    return(master_dm)

sessions1DF = buildDF(sessions1)

print(sessions1DF)
# ['val11', 'val2', 'val6', 'val5', 'val3', 'val8', 'val4', 'val9', 'val7', 'val10']


来源:https://stackoverflow.com/questions/51344283/for-in-loop-over-dict-gives-typeerror-string-indices-must-be-integers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!