Group dict elements based on a specified dict value

I have this data:

data = 
{
   "a":{
      "00066554466":{
         "Id":650,
         "Passwd":"e1c2a06545de9164d7e87cd98bed57c5",
         "zone":"Europe/Zurich"
      },
      "8745212300":{
         "Id":400,
         "Passwd":"ecb95502daace7f46bf12b484d086e5b",
         "zone":"Europe/Zurich"
      },
      "8745212301":{
         "Id":401,
         "Passwd":"ecb95502daace7f46bf12b484d086e5b",
         "zone":"Europe/Zurich"
      },
      "8745212302":{
         "DevId":402,
         "Passwd":"ecb95502daace7f46bf12b484d086e5b",
         "zone":"Europe/Zurich"
      }
   }
}

I would like to group keys with same Passwd. So result should be like the following.

{
   "e1c2a06545de9164d7e87cd98bed57c5":[
      "00066554466"
   ],
   "ecb95502daace7f46bf12b484d086e5b":[
      "8745212300",
      "8745212301",
      "8745212302"
   ]
}

I tried with itertools.groupby and with for k,v in xxx, but the result is never what I need.

>Solution :

itertools.groupby works well when then data is already sorted with values to be grouped in a successive order, which might not always be the case with your data.

Rather use dict.setdefault and a nested loop:

out = {}

for d1 in data.values():
    for k, d2 in d1.items():
        out.setdefault(d2['Passwd'], []).append(k)

print(out)

Variant with a defaultdict:

from collections import defaultdict

out = defaultdict(list)

for d1 in data.values():
    for k, d2 in d1.items():
        out[d2['Passwd']].append(k)

print(dict(out))

Output:

{'e1c2a06545de9164d7e87cd98bed57c5': ['00066554466'],
 'ecb95502daace7f46bf12b484d086e5b': ['8745212300', '8745212301', '8745212302']}

Leave a Reply