jinja groupby with iteritems()
jinja groupby with iteritems()
I have a dictionary
a:
attr1: abc
attr2: fddf
b:
attr1: abc
attr2: djfkdjf
...
I want to group by 'attr1'. I know I can do the following
groupby('attr1') %
something
% endfor %
But this is not what I want, because when I use values(), I lose the keys.
I need to use iteritems(), but it returns a list of tuples, which won't work with groupby
2 Answers
2
I believe that dict2items | groupby('value.attr1')
will do what you want, although due to the lack of items2dict
, you'll have to glue the "value" side of the answer back together by hand:
dict2items | groupby('value.attr1')
items2dict
- set_fact:
reassembled: |
dict2items
% set a_key = grouper[0] %
% set d = dict() %
% for it in grouper[1] %
% set _ = d.update(it["key"]: it["value"]) %
% endfor %
the key = a_key and d= d
% endfor %
I'll wait patiently for techraf to point out the more succinct way of doing that, but since no one else was chiming in, I thought I'd take a stab at it.
It turns out that groupby supports index. Instead of values() use items()
I achieved it by this
groupby('1.attr1') %
something
% endfor %
Thanks for contributing an answer to Stack Overflow!
But avoid …
To learn more, see our tips on writing great answers.
Required, but never shown
Required, but never shown
By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy
note the difference between values() and items(); values() returns something like [attr1: abc, attr2: fddf, attr1: abc, attr2: djfkdjf] while items return [(a, attr1: abc, attr2: fddf), (b, attr1: abc, attr2: djfkdjf)], so you'll need to group by a child attribute, but here you can't specify the child attribute because you don't know the parent's name
– laocius
Oct 2 '18 at 1:52