Home > other >  Grouping Python dictionary by 2nd item in key tuple
Grouping Python dictionary by 2nd item in key tuple

Time:01-31

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.

CodePudding user response:

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}}

CodePudding user response:

from collections import defaultdict

result = defaultdict(dict)
for key, value in my_dict.items():
  name, idk = key
  result[idk][name] = value
  • Related