Creating a new dict from a list of dicts

Viewed 48

I have a list of dictionaries in the following format

data = [
    {
    "Members": [
         "user11",
         "user12",
         "user13"
    ],
    "Group": "Group1"
    },
    {
    "Members": [
         "user11",
         "user21",
         "user22",
         "user23"
    ],
    "Group": "Group2"
    },
    {
    "Members": [
         "user11",
         "user22",
         "user31",
         "user32",
         "user33",
    ],
    "Group": "Group3"
    }]

I'd like to return a dictionary where every user is a key and the value is a list of all the groups which they belong to. So for the above example, this dict would be:

newdict = {
    "user11": ["Group1", "Group2", "Group3"]
    "user12": ["Group1"],
    "user13": ["Group1"],
    "user21": ["Group2"],
    "user22": ["Group2", "Group3"],
    "user23": ["Group2"],
    "user31": ["Group3"],
    "user32": ["Group3"],
    "user33": ["Group3"],
}

My initial attempt was using a defaultdict in a nested loop, but this is slow (and also isn't returning what I expected). Here was that attempt:

user_groups = defaultdict(list)
for user in users:
    for item in data:
        if user in item["Members"]:
            user_groups[user].append(item["Group"])

Does anyone have any suggestions for improvement for speed, and also just a generally better way to do this?

1 Answers

Code

new_dict = {}
for d in data:   # each item is dictionary
  members = d["Members"]
  for m in members:
    # appending corresponding group for each member
    new_dict.setdefault(m, []).append(d["Group"])


print(new_dict)

Out

{'user11': ['Group1', 'Group2', 'Group3'],
 'user12': ['Group1'],
 'user13': ['Group1'],
 'user21': ['Group2'],
 'user22': ['Group2', 'Group3'],
 'user23': ['Group2'],
 'user31': ['Group3'],
 'user32': ['Group3'],
 'user33': ['Group3']}
Related