如何返回列表/词典

2024-09-26 18:13:57 发布

您现在位置:Python中文网/ 问答频道 /正文

def pluglistafamilia():
    data = connect('GET', '/plugins/families')
    return list((h['id']) for h in data['family'])

def getfamilia():
    data = connect('GET', '/plugins/families')
    return dict((h['count'], h['name'], h['id']) for h in data['family'])


if __name__ == '__main__':
    token = login(username, password)
    d = getfamilia()

    print d

当我试图打印列表或词典时,收到以下错误消息。我知道我的语法可能错了。我还是个初学者。你知道吗

TypeError: list indices must be integers, not str


Tags: nameinidfordatagetreturndef
1条回答
网友
1楼 · 发布于 2024-09-26 18:13:57

如果不知道您使用的是什么API,就无法判断您在哪个部分出错。听起来datah是一行中的列表:

return dict((h['count'], h['name'], h['id']) for h in data['family'])

然而,当你开始工作的时候,你也会遇到另一个问题。你知道吗

In [2]: dict((1,2,3))
                                     -
TypeError                                 Traceback (most recent call last)
<ipython-input-2-0c2872d03334> in <module>()
  > 1 dict((1,2,3))

TypeError: cannot convert dictionary update sequence element #0 to a sequence

我不知道你的字典应该是什么样子,但你更适合做一个dict comp。你知道吗

return {h['count']: (h['name'], h['id']) for h in data['family']}
# or something like that...

相关问题 更多 >

    热门问题