Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将键值对添加到dict_Python_Django_List_Dictionary_Key - Fatal编程技术网

Python 将键值对添加到dict

Python 将键值对添加到dict,python,django,list,dictionary,key,Python,Django,List,Dictionary,Key,在以下代码中,我在“row[header]”处得到一个错误: for field in Document._meta.get_fields(): headers.append(field.name) docs = Document.objects.order_by('id') for doc in docs: row = {} for header in headers: if hasattr(doc, header): row[

在以下代码中,我在“row[header]”处得到一个错误:

for field in Document._meta.get_fields():
    headers.append(field.name)

docs = Document.objects.order_by('id')
for doc in docs:
    row = {}
    for header in headers:
        if hasattr(doc, header):
            row[header] = getattr(doc, header)
    files.append(row)
Python说:TypeError:列表索引必须是整数或片,而不是str

出了什么问题

Python回溯:

Traceback (most recent call last):
  File "/home/niels/PycharmProjects/sitesv/env/lib/python3.5/site-packages/django/core/handlers/exception.py", line 34, in inner
    response = get_response(request)
  File "/home/niels/PycharmProjects/sitesv/env/lib/python3.5/site-packages/django/core/handlers/base.py", line 126, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/home/niels/PycharmProjects/sitesv/env/lib/python3.5/site-packages/django/core/handlers/base.py", line 124, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/home/niels/PycharmProjects/sitesv/files/views.py", line 87, in get_file_list
    row[header] = getattr(doc, header)
TypeError: list indices must be integers or slices, not str

根据评论确认答案:

变量
已处于更高的作用域,因此对它的写入会被另一个线程对它的写入覆盖


行的名称
更改为其他名称会使问题消失。

能否发布Python提供的完整回溯?错误消息中定义了您的问题。您正在使用字符串为列表编制索引,但需要使用切片或int为列表编制索引。行={}定义一个dict,而不是列表,否?将行
row[header]=getattr(doc,header)
拆分为两行:
rh=getattr(doc,header)
然后
row[header]=rh
。这至少可以解决该行的哪一部分出错的问题。我想不出怎么做,但您的代码的行为就像row变量在全局范围内,而另一个线程将其撞坏。