#2269·jinja

Something wrong occurred when generating a string for `UserDict`

Author: Q7xM4Created Sep 10, 2026Updated Sep 16, 2026

When I tried to generate a string for UserDict, the result was incorrect. For ease of reproduction, here is a test.

from collections import UserDict
from jinja2 import Environment

model = Environment().from_string('{{ q|urlencode }}')
myUser = UserDict({"Aa": "[email protected]", "Bb": "[email protected]"})
print(model.render(q=myUser))

The result that I expect to obtain is:

Aa=PersonA%40123.com&Bb=PersonB%40123.com

Actually, I obtain:

A=a&B=b

Then I make some changes to the code. I changed UserDict({"Aa": "[email protected]", "Bb": "[email protected]"}) to UserDict({"A": "[email protected]", "B": "[email protected]"}) This time, an error will be reported directly.

Traceback (most recent call last):
  File "/home/test.py", line 19, in <module>
    print(model.render(q=myUser))
          ^^^^^^^^^^^^^^^^^^^^^^
  File "/home/jinja/src/jinja2/environment.py", line 1292, in render
    self.environment.handle_exception()
  File "/home/jinja/src/jinja2/environment.py", line 941, in handle_exception
    raise rewrite_traceback_stack(source=source)
  File "<template>", line 1, in top-level template code
  File "/home/jinja/src/jinja2/filters.py", line 173, in do_urlencode
    return "&".join(
           ^^^^^^^^^
  File "/home/jinja/src/jinja2/filters.py", line 174, in <genexpr>
    f"{url_quote(k, for_qs=True)}={url_quote(v, for_qs=True)}" for k, v in items
                                                                   ^^^^
ValueError: not enough values to unpack (expected 2, got 1)

Environment:

  • Python version: Python 3.12.3
  • Jinja version: Jinja2-3.2.0.dev0