244

I have an error message on Django 1.4:

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

It happened when I tried using a template tag like: {% for v in values %}:

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

It happens too when I try to access on a 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

The code is:

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

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

I'm just trying to access the value. I don't understand the "update sequence" message. When I use a cursor instead of hstore queryset, the function works. The error comes on template rendering too. I just restarted uwsgi and everything works well, but the error comes back later.

user2575627
  • 2,451
  • 2
  • 13
  • 5
  • Please post the code that shows what's in `values` and `tmp`. While code is missing, -1 (possibly temporary) for this question. – ElmoVanKielmo Jul 12 '13 at 08:51
  • 1
    I will add it as a comment. I got the error because I used a list instead of tuple. This raises the error: `dict(['A',"b"])` while this doesn't `dict([('A',"b")])` – NelsonGon Jun 18 '19 at 11:43

24 Answers24

517

Just ran into this problem. I don't know if it's the same thing that hit your code, but for me the root cause was because I forgot to put name= on the last argument of the url (or path in Django 2.0+) function call.

For instance, the following functions throw the error from the question:

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

But these actually work:

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

The reason why the traceback is unhelpful is because internally, Django wants to parse the given positional argument as the keyword argument kwargs, and since a string is an iterable, an atypical code path begins to unfold. Always use name= on your urls!

Thane Brimhall
  • 9,256
  • 7
  • 36
  • 50
  • 57
    This answer is very good because it covers an obscure error that is difficult to figure out. Even seasoned Django developers may fall in this particular trap. – glarrain Apr 11 '16 at 19:04
  • 5
    Especially if you also use the `Router.register` method of Django RestFramework. It looks very similar, the difference is the `name` kwarg... – Risadinha Jul 06 '16 at 09:49
  • 2
    FYI I also received this error using Django 2.0 style `path` URL. Forgot to use the kwarg and had this: `path('foo/', views.foo, 'foo')`. I had to change to `path('foo/', views.foo, name='foo')` – inostia Aug 15 '19 at 21:16
  • 1
    @inostia That's a good point. I'll update the answer to let people know that the issue still persists. – Thane Brimhall Aug 17 '19 at 03:29
  • 1
    I know its late, But this is brilliant insight into how django is considering the args passed. Thanks for the explanation. – Gru Nov 02 '19 at 11:06
105

I got this error when I was messing around with string and dictionary.

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

So what you actually got to do to get dict from string is:

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

Or in matter of security we can use literal_eval

from ast import literal_eval
Taras Vaskiv
  • 2,215
  • 1
  • 18
  • 17
33

Error in your question is raised when you try something like following:

>>> 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

It's hard to tell where is the cause in your code unless you show your code, full traceback.

falsetru
  • 357,413
  • 63
  • 732
  • 636
  • 6
    This confirms that the cause is not included in the question. – ElmoVanKielmo Jul 12 '13 at 08:54
  • Thanks for the answer next time I will copy the traceback, but it's weird, when it happened with the template tag, just after uwsgi restart, the result displayed properly, so there was result – user2575627 Jul 12 '13 at 09:12
  • 2
    @user2575627, Why don't you post code/traceback now? Update (edit) your question. – falsetru Jul 12 '13 at 09:13
  • Sorry, I didn't post code/traceback because it was urgent to repair/fix the service, so I didn't copy the traceback the first time – user2575627 Jul 15 '13 at 13:37
  • @user2575627, Could you post codes around /home/name/workspace/project/app/data/commands/my_command.py line 60? – falsetru Jul 15 '13 at 13:42
19

I faced the above mentioned problem when I forgot to pass a keyword argument name to url() function.

Code with error

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

Code without error

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

So finally I removed the above error in this way. It might be something different in your case. So check your url patterns in urls.py.

hygull
  • 8,464
  • 2
  • 43
  • 52
17

Here is how I encountered this error in Django and fixed it:

Code with error

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

Correction

urlpatterns = [path('home/', views.home, name='home'),]
trincot
  • 317,000
  • 35
  • 244
  • 286
Harshit Gangwar
  • 553
  • 7
  • 14
10

Solution»

Pass a keyword argument name with value as your view name e.g home or home-view etc. to url() function.

Throws Error»

url(r'^home$', 'common.views.view1', 'home'),

Correct»

url(r'^home$', 'common.views.view1', name='home'),

kvantour
  • 25,269
  • 4
  • 47
  • 72
9

Here is the reproduced error.

>>> 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
>>> 

If you give the sequence and any element length is 1 and required two then we will get this kind of error. See the above code. First time I gave the sequence with tuple and it's length 1, then we got the error and dictionary is not updated. second time I gave inside tuple with with two elements, dictionary got updated.

neotam
  • 2,611
  • 1
  • 31
  • 53
  • I'm getting the same error using shortucts.redirect and trying to send the response to an external page.. e.g. ' [code] return redirect("https://msn.com")[/code] – roblem Aug 29 '17 at 20:28
4

I got the same issue and found that it was due to wrong parameters. In views.py, I used:

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

But I found the issue: {'items', items}. Changing to {'items': items} resolved the issue.

fragilewindows
  • 1,394
  • 1
  • 15
  • 26
Binoy Babu
  • 41
  • 1
3

Another scenario that causes this error:

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

One way to achieve what you want is to use eval

eval('{"a":1}')  # gives {"a":1}
LoMaPh
  • 1,476
  • 2
  • 20
  • 33
3

I had the same problem and it turned out that missing 'name' in the urls.py was the cause of problem.

2

In my case, my get_context_data in one of my views was returning return render(self.request, 'es_connection_error.html', {'error':error}); in a try/catch block instead of returning context

Shadi
  • 9,742
  • 4
  • 43
  • 65
2

The error should be with the params. Please verify that the params is a dictionary object. If it is just a list/tuple of arguments use only one * (*params) instead of two * (**params). This will explode the list/tuple into the proper amount of arguments.

Or, if the params is coming from some other part of code as a JSON file, please do json.loads(params), because the JSON objects sometimes behave as string and so you need to make it as a JSON using load from string (loads).

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

Hope this helps!

MLavrentyev
  • 1,827
  • 2
  • 24
  • 32
Midhun C Nair
  • 136
  • 1
  • 5
2

check in your dictionary whether if you have single or double Quotation mark in your key or value!

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

to resolve it you can simply convert your dictionary in to string and then use replace method!

shailu
  • 190
  • 1
  • 10
2

I faced this problem when I was trying to convert json string to dict.

Input: '{\r\n "resource_id": "id",\r\n "resource_type": "resource"\r\n}'

Using dict() to convert the string to dict gave me this error. The correct way would be to use json module.

Example: json.loads(input_str)

Faizi
  • 410
  • 1
  • 8
  • 13
2
urlpatterns = [ 
    path('',HomePageView.as_view(),name='home'),
]
Tyler2P
  • 2,324
  • 26
  • 22
  • 31
  • 1
    Your answer could be improved by adding more information on what the code does and how it helps the OP. – Tyler2P Jan 31 '22 at 20:03
1

I encountered this issue when trying to invoke the update method with a parameter of a wrong type. The expected dict was:

{'foo': True}

The one that was passed was:

{'foo': "True"}

make sure you check all the parameters you pass are of the expected type.

Nick Kobishev
  • 157
  • 4
  • 13
1

I too had a similar type of problem . The solution is simple . just dont try to enter NULL or None value in values or u might have to use Something like this
dic.update([(key,value)])

yunus
  • 2,445
  • 1
  • 14
  • 12
1

I hit this error calling:

dict(my_data)

I fixed this with:

import json

json.loads(my_data)
duhaime
  • 25,611
  • 17
  • 169
  • 224
  • this solution will cause another error `Expecting property name enclosed in double quotes` if `my_dict` have `keys` in `single_quotes` for **Example** ```my_dict = {'single' : true}``` – Azhar Uddin Sheikh Aug 17 '22 at 06:34
0

You are sending one parameter incorrectly; it should be a dictionary object:

  • Wrong: func(a=r)

  • Correct: func(a={'x':y})

SiHa
  • 7,830
  • 13
  • 34
  • 43
soField
  • 2,536
  • 9
  • 36
  • 44
0

This behavior will also occurs when using get_or_create method in the following example below one will obviously get that error:

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

To resolve this you will add the the respective key and value.

i.e like this state,_ = Status.objects.get_or_create(name='Pending')

Philip Mutua
  • 6,016
  • 12
  • 41
  • 84
0

Please check your URL path I fixed this issue by changing the URL.

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

Instead of use

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

  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jan 29 '22 at 19:22
0

I was getting this issue so this is how I solved it ( by doing an eval and 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)

The data I was reading was a text file with a dictionary objects

{'unknown': 298, 'a4a815d631c805ccd10dd2f1548baa57': 9724, '22b5a0ff959ce0b4036716cc0c2df68b': 1341, 'd186fde596dffaab46260765c7fcba61': 2052}
{'unknown': 323, '49e5357782510659cf083356f7d2a1ab': 9826, 'a4a815d631c805ccd10dd2f1548baa57': 9812, 'b615930608b8dcd217de7904d4463efb': 2409}
AGN Gazer
  • 8,025
  • 2
  • 27
  • 45
Aseem Jain
  • 333
  • 2
  • 7
0
from ast import literal_eval

c = "{'taras': 'vaskiv', 'iruna': 'vaskiv'}"
c= dict(literal_eval(c))
  • 2
    Welcome to Stack Overflow! While this code may solve the question, [including an explanation](//meta.stackexchange.com/q/114762) of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please [edit] your answer to add explanations and give an indication of what limitations and assumptions apply. – Yunnosch May 01 '23 at 05:56
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community May 02 '23 at 06:49
0

I got this error when I was messing around with string and dictionary.

dict1 = {'taras': 'vaskiv', 'iruna': 'vaskiv'}
str1 = str(dict1)
dict(str1)
or to be specific
query_result = req_db_session.query(app_config_model.APPCONFIG).with_entities(app_config_model.APPCONFIG.value).filter(app_config_model.APPCONFIG.name == 'test_me').first()
print(query_result, type(query_result))
print('--------------------------')
print(type(query_result))
# prints <class 'sqlalchemy.util._collections.result'>
print(dict(query_result))
# throws error
*** ValueError: dictionary update sequence element #0 has length 1; 2 is required So what you actually worked was:

query_result = req_db_session.query(app_config_model.APPCONFIG).with_entities(app_config_model.APPCONFIG.value).filter(app_config_model.APPCONFIG.name == 'test_me').first()
print(query_result, type(query_result))
print('--------------------------')
print(type(query_result.value))
# prints <type 'unicode'>
print(json.loads(query_result.value))
# prints parsed dictionary