简体   繁体   English

从字典列表创建一个新字典

[英]Creating a new dict from a list of dicts

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:所以对于上面的例子,这个 dict 将是:

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).我最初的尝试是在嵌套循环中使用 defaultdict,但这很慢(而且也没有返回我所期望的)。 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?有没有人有任何改进速度的建议,以及通常更好的方法?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM