TypeError:尝试向python列表中添加其他属性时,无法调用“dict”对象

2024-04-19 21:38:02 发布

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

我试图将带有两个返回为data内的json值的python列表附加到我的final_list

我的代码:

    data = json.loads(r.text)
    final_list = []
    for each_req in data:
        final_list.append(each_req(['requestId'],['author']))
    return final_list

错误:

TypeError: 'dict' object is not callable

如果我尝试相同的方法,但只使用requestId,效果很好:

    data = json.loads(r.text)
    final_list = []
    for each_req in data:
        final_list.append(each_req['requestId'])
    return final_list

然后列表中包含“12345”等值

如何将最终列表附加为如下所示:

'12345 John Doe'


Tags: 代码textinjson列表fordatareturn
3条回答

您需要再次访问字典才能将值附加到列表中

试试这个:

final_list.append(each_req['requestId'] + each_req['author'])

做一些类似于:

tup = (each_req['requestId'], each_req['author'])
final_list.append(tup)

each_req()意味着它是一个函数和/或在某种程度上是可调用的,而它不是,因此出现了错误

假设您的 数据类似于data={'key1':{'requestId':12345,'author':'Myname'} 因为'data'中的i返回字典中的'keys',而i['key1']不会返回值 那把钥匙的钥匙

然后试试这个代码

def foo():
    data = {'key1':{'requestId':12345,'author':'Myname'}}
    final_list = []
    for each_req in data:
        final_list.append(f"{data[each_req]['requestId']} {data[each_req]['author']}")
    return final_list

print(foo())

相关问题 更多 >