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

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.

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

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