Home > Software engineering >  Group dict elements based on a specified dict value
Group dict elements based on a specified dict value

Time:01-17

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.

CodePudding user response:

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

CodePudding user response:

One solution, but probably not the pythonic is just to do:

passwd_group = {}

for k, val in data["a"]:

    if val["Passwd"] not in passwd_group:
        passwd_group[val["Passwd"]] = []

    passwd_group.append(k)
    

CodePudding user response:

This may not be ideal but got it working.

new_dict = {}
for L in data.keys():
    x = data[L]
    for M in x.keys():
        y = x[M]
        for N in y.keys():
            if N == "Passwd":
                new_list = new_dict.get(y[N], [])
                new_list.append(M)
                new_dict[y[N]] = new_list
print(new_dict)
  • Related