title: How can I modify/merge Jinja2 dictionaries?
body: <p>I have a Jinja2 dictionary and I want a single expression that modifies it - either by changing its content, or merging with another dictionary.</p>
  
  <pre><code>&gt;&gt;&gt; import jinja2
  &gt;&gt;&gt; e = jinja2.Environment()
  </code></pre>
  
  <p>Modify a dict: Fails.</p>
  
  <pre><code>&gt;&gt;&gt; e.from_string("{{ x[4]=5 }}").render({'x':{1:2,2:3}})
  Traceback (most recent call last):
    File "&lt;stdin&gt;", line 1, in &lt;module&gt;
    File "jinja2/environment.py", line 743, in from_string
      return cls.from_code(self, self.compile(source), globals, None)
    File "jinja2/environment.py", line 469, in compile
      self.handle_exception(exc_info, source_hint=source)
    File "&lt;unknown&gt;", line 1, in template
  jinja2.exceptions.TemplateSyntaxError: expected token
                                              'end of print statement', got '='
  </code></pre>
  
  <p>Two-stage update: Prints superfluous "None".</p>
  
  <pre><code>&gt;&gt;&gt; e.from_string("{{ x.update({4:5}) }} {{ x }}").render({'x':{1:2,2:3}})
  u'None {1: 2, 2: 3, 4: 5}'
  &gt;&gt;&gt; e.from_string("{{ dict(x.items()+ {3:4}.items()) }}").render({'x':{1:2,2:3}})
  Traceback (most recent call last):
    File "&lt;stdin&gt;", line 1, in &lt;module&gt;
    File "jinja2/environment.py", line 868, in render
      return self.environment.handle_exception(exc_info, True)
    File "&lt;template&gt;", line 1, in top-level template code
  TypeError: &lt;lambda&gt;() takes exactly 0 arguments (1 given)
  </code></pre>
  
  <p>Use <code>dict(x,**y)</code>: Fails.</p>
  
  <pre><code>&gt;&gt;&gt; e.from_string("{{ dict((3,4), **x) }}").render({'x':{1:2,2:3}})
  Traceback (most recent call last):
    File "&lt;stdin&gt;", line 1, in &lt;module&gt;
    File "jinja2/environment.py", line 868, in render
      return self.environment.handle_exception(exc_info, True)
    File "&lt;template&gt;", line 1, in top-level template code
  TypeError: call() keywords must be strings
  </code></pre>
  
  <p>So how does one modify the dictionary <code>x</code> in Jinja2 by changing an attribute or merging with another dictionary?</p>
  
  <p>This question is similar to: <a href="https://stackoverflow.com/questions/38987/how-can-i-merge-two-python-dictionaries-as-a-single-expression">How can I merge two Python dictionaries as a single expression?</a> -- insofar as Jinja2 and Python are analogous.</p>