Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge two dictionaries in Jinja2

I have some code which basically searches some YAML files for Jinja2 variables and replaces them where appropriate. I want to be able to combine to YAML dicts together and was looking for a way to do this using the default Jinja2 library.

Here is some example YAML of what I am trying to a achieve:


vars.yml

vars:
  default:
    name: test1
    location: UK
  new:
    name: test2
    country: UK

template.yml

test: {{ vars.default.update(vars.new) }}

This would ideally output something like:

output.yml

test:
  name: test2
  location : UK
  country: UK

I am looking for a way to merge two dictionaries together using this method. The Jinja2 documentation don't appear to have an inbuilt function like the Ansible combine filter.

Is it possible that I just import this feature into my code or create a similar feature? I noticed that it is not included in the standard library for Ansible Jinja2 filters

When trying to use the update filter (which doesn't appear to exist in the Jinja2 documentation) I get a None result.

like image 969
craigthackerx Avatar asked Oct 17 '25 00:10

craigthackerx


1 Answers

The update method of a dictionary is actually updating the source dictionary, not returning the merged dictionaries.

update([other])
Update the dictionary with the key/value pairs from other, overwriting existing keys. Return None.

Source: https://docs.python.org/3/library/stdtypes.html#dict.update

So, you have two ways of achieving it:

  • either you have the expression-statement extension loaded and you can use the {% do ... %} construct:
    {% do vars.default.update(vars.new) -%}
    test: {{ vars.default }}
    
  • or it is not activated and you can use a dummy assignation:
    {% set noop = vars.default.update(vars.new) -%}
    test: {{ vars.default }}
    
like image 127
β.εηοιτ.βε Avatar answered Oct 19 '25 14:10

β.εηοιτ.βε



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!