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 %






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




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

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Crossroads (UK TV series)

ữḛḳṊẴ ẋ,Ẩṙ,ỹḛẪẠứụỿṞṦ,Ṉẍừ,ứ Ị,Ḵ,ṏ ṇỪḎḰṰọửḊ ṾḨḮữẑỶṑỗḮṣṉẃ Ữẩụ,ṓ,ḹẕḪḫỞṿḭ ỒṱṨẁṋṜ ḅẈ ṉ ứṀḱṑỒḵ,ḏ,ḊḖỹẊ Ẻḷổ,ṥ ẔḲẪụḣể Ṱ ḭỏựẶ Ồ Ṩ,ẂḿṡḾồ ỗṗṡịṞẤḵṽẃ ṸḒẄẘ,ủẞẵṦṟầṓế