我在Django 1.4上有一个错误消息:

dictionary update sequence element #0 has length 1; 2 is required

它发生在我尝试使用模板标签,如:{% v在值%}:

dictionary update sequence element #0 has length 1; 2 is required

Request Method:     GET
Request URL:    ...
Django Version:     1.4.5
Exception Type:     ValueError
Exception Value:    

dictionary update sequence element #0 has length 1; 2 is required

Exception Location:     /usr/local/lib/python2.7/dist-packages/djorm_hstore/fields.py in __init__, line 21
Python Executable:  /usr/bin/uwsgi-core
Python Version:     2.7.3
Python Path:    

['/var/www/',
 '.',
 '',
 '/usr/lib/python2.7',
 '/usr/lib/python2.7/plat-linux2',
 '/usr/lib/python2.7/lib-tk',
 '/usr/lib/python2.7/lib-old',
 '/usr/lib/python2.7/lib-dynload',
 '/usr/local/lib/python2.7/dist-packages',
 '/usr/lib/python2.7/dist-packages',
 '/usr/lib/python2.7/dist-packages/PIL',
 '/usr/lib/pymodules/python2.7']

Server time:    sam, 13 Jul 2013 16:15:45 +0200
Error during template rendering

In template /var/www/templates/app/index.html, error at line 172
dictionary update sequence element #0 has length 1; 2 is required

172     {% for product in products %}

Traceback Switch to copy-and-paste view

/usr/lib/python2.7/dist-packages/django/core/handlers/base.py in get_response

                            response = callback(request, *callback_args, **callback_kwargs)

    ...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/contrib/auth/decorators.py in _wrapped_view

                    return view_func(request, *args, **kwargs)

    ...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/views/decorators/http.py in inner

                return func(request, *args, **kwargs)

    ...
▶ Local vars
./app/views.py in index

            context_instance=RequestContext(request))

    ...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/shortcuts/__init__.py in render_to_response

        return HttpResponse(loader.render_to_string(*args, **kwargs), **httpresponse_kwargs)

    ...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/template/loader.py in render_to_string

            return t.render(context_instance)

    ...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/template/base.py in render

                return self._render(context)

    ...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/template/base.py in _render

            return self.nodelist.render(context)

    ...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/template/base.py in render

                    bit = self.render_node(node, context)

    ...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/template/debug.py in render_node

                return node.render(context)

    ...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/template/loader_tags.py in render

            return compiled_parent._render(context)

    ...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/template/base.py in _render

            return self.nodelist.render(context)

    ...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/template/base.py in render

                    bit = self.render_node(node, context)

    ...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/template/debug.py in render_node

                return node.render(context)

    ...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/template/loader_tags.py in render

                result = block.nodelist.render(context)

    ...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/template/base.py in render

                    bit = self.render_node(node, context)

    ...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/template/debug.py in render_node

                return node.render(context)

    ...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/template/defaulttags.py in render

            len_values = len(values)

    ...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/core/paginator.py in __len__

            return len(self.object_list)

    ...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/db/models/query.py in __len__

                    self._result_cache = list(self.iterator())

    ...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/db/models/query.py in iterator

                        obj = model(*row[index_start:aggregate_start])

    ...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/db/models/base.py in __init__

                    setattr(self, field.attname, val)

    ...
▶ Local vars
/usr/local/lib/python2.7/dist-packages/djorm_hstore/fields.py in __set__

                value = self.field._attribute_class(value, self.field, obj)

    ...
▶ Local vars
/usr/local/lib/python2.7/dist-packages/djorm_hstore/fields.py in __init__

            super(HStoreDictionary, self).__init__(value, **params)

    ...
▶ Local vars

当我尝试访问hstore queryset时,也会发生这种情况:

Traceback (most recent call last):
File "manage.py", line 14, in <module>
    execute_manager(settings)

File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 459, in execute_manager
    utility.execute()

File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 382, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)

File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 196, in run_from_argv
    self.execute(*args, **options.__dict__)

File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 232, in execute
    output = self.handle(*args, **options)

File "/home/name/workspace/project/app/data/commands/my_command.py", line 60, in handle
    item_id = tmp[0].id,

File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 207, in __getitem__
    return list(qs)[0]

File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 87, in __len__
    self._result_cache.extend(self._iter)

File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 301, in iterator
    obj = model(*row[index_start:aggregate_start])

File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py", line 300, in __init__
    setattr(self, field.attname, val)

File "/usr/local/lib/python2.7/dist-packages/djorm_hstore/fields.py", line 38, in __set__
    value = self.field._attribute_class(value, self.field, obj)

File "/usr/local/lib/python2.7/dist-packages/djorm_hstore/fields.py", line 21, in __init__
    super(HStoreDictionary, self).__init__(value, **params)

ValueError: dictionary update sequence element #0 has length 1; 2 is required

代码是:

tmp = Item.objects.where(HE("kv").contains({'key':value}))

if tmp.count() > 0:
            
    item_id = tmp[0].id,

我只是想求值。我不明白“更新序列”消息。当我使用游标而不是hstore queryset时,该函数工作。错误也出现在模板渲染上。我刚刚重新启动了uwsgi,一切正常,但错误稍后又回来了。


当你尝试以下内容时,你的问题会出现错误:

>>> a_dictionary = {}
>>> a_dictionary.update([[1]])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: dictionary update sequence element #0 has length 1; 2 is required

除非你展示你的代码,完整的回溯,否则很难在你的代码中找到原因。


刚刚遇到了这个问题。我不知道这是否与你的代码相同,但对我来说,根本原因是因为我忘记在url(或Django 2.0+中的路径)函数调用的最后一个参数上加上name=。

例如,下面的函数会抛出问题中的错误:

url(r'^foo/(?P<bar>[A-Za-z]+)/$', views.FooBar.as_view(), 'foo')
path('foo/{slug:bar}/', views.FooBar, 'foo')

但这些确实有用:

url(r'^foo/(?P<bar>[A-Za-z]+)/$', views.FooBar.as_view(), name='foo')
path('foo/{slug:bar}/', views.FooBar, name='foo')

回溯没有帮助的原因是,Django内部希望将给定的位置参数解析为关键字参数kwargs,而由于字符串是可迭代对象,因此开始展开非典型的代码路径。在你的url上总是使用name= !


这是复制错误。

>>> d = {}
>>> d.update([(1,)])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: dictionary update sequence element #0 has length 1; 2 is required
>>> 
>>> d
{}
>>> 
>>> d.update([(1, 2)])
>>> d
{1: 2}
>>> 
>>> d.update('hello_some_string')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>  
ValueError: dictionary update sequence element #0 has length 1; 2 is required
>>> 

如果你给出一个序列,任意元素长度为1并且需要两个,那么我们就会得到这种错误。 请参阅上面的代码。第一次我给出了长度为1的tuple序列,然后我们得到了错误,字典没有更新。第二次我给内部元组与两个元素,字典得到更新。


您错误地发送了一个参数;它应该是一个字典对象:

错误:func (= r) 正确的:func(={“x”:y})


我遇到了同样的问题,发现这是由于错误的参数。 在views.py中,我使用了:

return render(request, 'demo.html',{'items', items})    

但是我发现了问题:{'items', items}。更改为{'items': items}解决了该问题。


我在尝试用错误类型的参数调用更新方法时遇到了这个问题。 期望的字典是:

{'foo': True}

通过的是:

{'foo': "True"}

确保您检查您传递的所有参数都是预期的类型。


在我的例子中,我的get_context_data在我的一个视图返回返回渲染(self。Request, 'es_connection_error.html', {'error':error});在try/catch块中,而不是返回上下文


当我忘记将关键字参数名称传递给url()函数时,我遇到了上述问题。

错误代码

 url(r"^testing/$", views.testing, "testing")

没有错误的代码

url(r"^testing/$", views.testing, name="testing")

所以最后我用这种方法去掉了上面的错误。你的情况可能有所不同。检查urls。py中的url模式。


答案»

向url()函数传递一个带值的关键字参数名作为视图名,例如home或home-view等。

抛出错误”

url (^ home ',’common观点。view1’、’home’)

正确性»

url (^ home ',’common观点。view1’,名称=’home’);


错误应该与参数有关。请验证params是一个字典对象。如果它只是一个参数列表/元组,只使用一个* (*params)而不是两个* (**params)。这将把list/tuple分解成适当数量的参数。

或者,如果params来自其他部分的代码作为JSON文件,请执行JSON .loads(params),因为JSON对象有时表现为字符串,因此您需要使用load from string (loads)将其作为JSON。

super(HStoreDictionary, self).__init__(value, **params)

希望这能有所帮助!


我在处理字符串和字典的时候得到了这个错误。

dict1 = {'taras': 'vaskiv', 'iruna': 'vaskiv'}
str1 = str(dict1)
dict(str1)
*** ValueError: dictionary update sequence element #0 has length 1; 2 is required

所以你实际上要做的是从字符串中获取dict

dic2 = eval(str1)
dic2
{'taras': 'vaskiv', 'iruna': 'vaskiv'}

或者为了安全起见,我们可以使用literal_eval

from ast import literal_eval

我也有类似的问题。解决办法很简单。只是不要尝试在值中输入NULL或None值,否则你可能不得不使用类似thisdic.update([(键,值)])的东西


下面是我如何在Django中遇到这个错误并修复它:

错误代码

urlpatterns = [path('home/', views.home, 'home'),]

修正

urlpatterns = [path('home/', views.home, name='home'),]

我点击这个错误调用:

dict(my_data)

我解决了这个问题:

import json

json.loads(my_data)

在下面的例子中,使用get_or_create方法时也会发生这种行为,显然会得到错误:

state,_ = Status.objects.get_or_create('Pending')

要解决这个问题,您需要添加相应的键和值。

例如,像这样的状态,_ = Status.objects.get_or_create(name='Pending')


导致此错误的另一个场景:

dict('{"a":1}')  # gives the error

实现您想要的一种方法是使用eval

eval('{"a":1}')  # gives {"a":1}

在你的字典中检查你的键或值是否有单引号或双引号!

dict1 = {'hello': 'world', 'programmer's': 'have girlfriend'}

要解决这个问题,你可以简单地将你的字典转换为字符串,然后使用replace方法!


当我试图将json字符串转换为dict时,我遇到了这个问题。

输入:“{\ r \ n " resource_id ": " id ", \ r \ n“resource_type”:“资源”\ r \ n}”

使用dict()将字符串转换为dict给出了这个错误。正确的方法是使用json模块。

例如:json.loads (input_str)


urlpatterns = [ 
    path('',HomePageView.as_view(),name='home'),
]

请检查您的URL路径,我通过更改URL解决了这个问题。

路径('reset_password_email/', requestpasswordresetemail, "request-rest-email")

而不是使用

路径('reset_password_email/', requestpasswordresetemail, name="request-rest-email")


我也遇到了同样的问题,原来在urls.py中缺少'name'是问题的原因。


我得到了这个问题,所以这就是我如何解决它(通过做一个eval和strip)

aggr = {}
with open("output.txt", "r") as f:
    for line in f.readlines():
        for k, v in dict(eval(line.strip())).items():
            aggr.setdefault(k, 0)
            aggr[k] = aggr[k] + v
    
print(aggr)

print(aggr)

我读取的数据是一个带有字典对象的文本文件

{'unknown': 298, 'a4a815d631c805ccd10dd2f1548baa57': 9724, '22b5a0ff959ce0b4036716cc0c2df68b': 1341, 'd186fde596dffaab46260765c7fcba61': 2052}
{'unknown': 323, '49e5357782510659cf083356f7d2a1ab': 9826, 'a4a815d631c805ccd10dd2f1548baa57': 9812, 'b615930608b8dcd217de7904d4463efb': 2409}