添加键值对dict
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了添加键值对dict相关的知识,希望对你有一定的参考价值。
在以下代码中,我在'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:list indices必须是整数或切片,而不是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
答案
答案通过评论确认:
变量row
已经处于更高的范围,因此写入它会被另一个线程的写入覆盖。
将row
的名称更改为其他内容会使问题消失。
以上是关于添加键值对dict的主要内容,如果未能解决你的问题,请参考以下文章