Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Grouping Python dict by 2nd item in key tuple

I have a dict:

{(bob, CA): 90, (tom, NJ): 80, (sarah, CA): 90, (jon, TX): 90}

I would like to group by the 2nd item in the key tuple:

{CA: {bob: 90, sarah: 90},
NJ: {tom: 80},
TX: {jon: 90}}

I could formulate this by iterating through the original list, but wondering if there is a way to do this using itertools.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I have tried something along the lines of:

groupby(l, operator.itemgetter(list(l.keys())[0][1])):

but it is not working.

Any pointers are appreciated.

>Solution :

Here is one solution. It does the grouping logic by making use of dict.setdefault method.

>>> c = {('bob', 'CA'): 90, ('tom', 'NJ'): 80, ('sarah', 'CA'): 90, ('jon', 'TX'): 90}
>>> 
>>> result = {}
>>> for (first, second), value in c.items():
...     result.setdefault(second, {})[first] = value
... 
>>> print(result)
{'CA': {'bob': 90, 'sarah': 90}, 'NJ': {'tom': 80}, 'TX': {'jon': 90}}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading