Grouping Python dictionary by 2nd item in key tuple


I have a dictionary:

{(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.

I have tried something along the lines of:

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

but it is not working.

Asked By: Manas



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}}
Answered By: Abdul Niyas P M
from collections import defaultdict

result = defaultdict(dict)
for key, value in my_dict.items():
  name, idk = key
  result[idk][name] = value
Answered By: WingedSeal
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.