Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create DictMerge #24

Merged
merged 7 commits into from
Jun 10, 2024

Conversation

droans
Copy link
Contributor

@droans droans commented Mar 26, 2024

Adds ct_dict_merge as new function. Readme is updated with the function, description, and example.


It's annoyed me for too long that the only real way to merge dictionaries in HA templates is:

{% set dict_a = {'a': 1, 'b': 2} %}
{% set dict_b = {'c': 3, 'd': 4} %}

{# Current method #}
{% set dict_a_ls = dict_a.items() | list %}
{% set dict_b_ls = dict_b.items() | list %}
{% set dict_c = dict.from_items(dict_a_ls + dict_b_ls) %}

{# Or #}
{% set dict_c = dict.from_items(dict_a.items() | list + dict_b.items() | list) %}

{# New Method #}
{% set dict_c = dict_merge(dict_a, dict_b) %}

I'm just using a single one-liner list comprehension for this. There is no limit on the number of dictionaries that can be passed to the function.

Preferably, we should just be able to add two dicts together or use either dict.update or {% set dict.key = val %} but those moves are disallowed in the HA Jinja templates.

@ildar170975
Copy link

ildar170975 commented Mar 26, 2024

Interesting, could you share a possible real application for this function?
Please post your answer in Community (https://community.home-assistant.io/t/custom-templates/528378) to avoid cluttering your PR with this info.

Update: I see it is posted, thanks a lot!

@PiotrMachowski
Copy link
Owner

Neat idea 👍

@PiotrMachowski PiotrMachowski merged commit 39748dd into PiotrMachowski:dev Jun 10, 2024
2 checks passed
@PiotrMachowski
Copy link
Owner

Thank you, @droans!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants