Hello everyone,
I have a list:
{% set Players_Groups = [{'Sonos': 'media_player.bureau_sonos'}, {'Ios': 'parents'}] %}
I would like to select the Sonos and the Ios. This just won’t work…
Can someone help me on my way.
Thanks in advance.
Hello everyone,
I have a list:
{% set Players_Groups = [{'Sonos': 'media_player.bureau_sonos'}, {'Ios': 'parents'}] %}
I would like to select the Sonos and the Ios. This just won’t work…
Can someone help me on my way.
Thanks in advance.
It is a bit hard to guess what you want to achieve.
The variable already have the two values you want.
There are 2 dictionaries and I would like to have the 2 key names!
{{ Players_Group[0].Sonos }}
{{ Players_Group[1].Ios }}
Thanks for your response.
But I am looking for the 2 key names
{{ Players_Group[0].keys() | list }}
{{ Players_Group[1].keys() | list }}
I have this
{% for Type in SpelersGroep %}
{{Type.keys()}}
{% endfor %}
That results in
dict_keys(['Sonos'])
dict_keys(['Ios'])
But then I still don’t have the clean 'Sonos and Ios".
{% for Type in SpelersGroep %}
{{ Type.keys() | list }}
{% endfor %}
Or do you want the result to be a single list containing the two key names?
{% set Players_Groups = [{'Sonos': 'media_player.bureau_sonos'}, {'Ios': 'parents'}] %}
{% set ns = namespace(k=[]) %}
{% for x in Players_Groups %}
{% set ns.k = ns.k + [x.keys() | list | first] %}
{% endfor %}
{{ ns.k }}
Thank you very much.
That is what I was looking for
You’re welcome!
Here’s another way to do it. This one is better if each dict has multiple keys.
{% set Players_Groups = [{'Sonos': 'media_player.bureau_sonos'}, {'Ios': 'parents'}] %}
{% set ns = namespace(k=[]) %}
{% for x in Players_Groups %}
{% set ns.k = ns.k + [x.keys() | list ] %}
{% endfor %}
{{ ns.k | flatten }}
One more question: “What does that “|first” actually do?”
{% set SpelersGroep = [{'Sonos': 'media_player.bureau_sonos'}, {'Ios': 'parents'}] %}
{{ SpelersGroep|map('list')|sum(start=[])|list }}
That gives a list of keys.
{% set SpelersGroep = [{'Sonos': 'media_player.bureau_sonos'}, {'Ios': 'parents'}] %}
{{ " and ".join(SpelersGroep|map('list')|sum(start=[])|list) }}.
…although you probably need to explain exactly what you want.
It selects the value of the first item in the list.
Works great too! Thank you!
Today I learned that applying list
to a dict will return a list of its keys.
Tip:
With the recent introduction of flatten
it can be used instead of sum(start=[])
to “flatten” a list of lists into a simple list.
Apparently there is still a lot to learn.
A lifetime of learning.
One more question If I want the value now, how do I do that?
Replace x.keys()
with x.values()
{% set Players_Groups = [{'Sonos': 'media_player.bureau_sonos'}, {'Ios': 'parents'}] %}
{% set ns = namespace(k=[]) %}
{% for x in Players_Groups %}
{% set ns.k = ns.k + [x.values() | list ] %}
{% endfor %}
{{ ns.k | flatten }}