将字典值转换为Python中的键

groups_per_user 函数接收一个字典,其中包含组名称和用户列表。用户可以属于多个组。填写空白以返回一个字典,其中用户作为键,其组列表作为值


def groups_per_user(group_dictionary):

    user_groups = {}

    for key,values in group_dictionary.items():

        for users in values:

            user_groups[users] = user_groups.get(users,0)+1

    return(user_groups)


print(groups_per_user({"local": ["admin", "userA"],"public":  ["admin", "userB"],"administrator":         ["admin"] }))

# output must be {'admin':["local","public","administrator"],'userA':"local" ,'userB':"public"}

#output I am getting {'admin': 3, 'userA': 1, 'userB': 1}


吃鸡游戏
浏览 108回答 2
2回答

慕森王

您可以迭代当前dict并反转键值对:d = {"local": ["admin", "userA"], "public":  ["admin", "userB"], "administrator": ["admin"] }res = {}for k,v in d.items():    for e in v:        if e in res:            res[e].append(k)        else:            res[e] = [k]print(res)输出:{'admin': ['public', 'administrator', 'local'], 'userB': ['public'], 'userA': ['local']}   

Qyouu

请尝试下面的程序。它只是迭代 group_dictionary 的所有元素并构造 user_dictionary。def groups_per_user(group_dictionary):    user_groups=dict([(a,[]) for a in sum(group_dictionary.values(),list())])    for u in user_groups:        for g in group_dictionary:            if u in group_dictionary[g]:                user_groups[u].append(g)    return(user_groups)print(groups_per_user({"local": ["admin", "userA"],"public":  ["admin", "userB"],"administrator":         ["admin"] }))输出{'admin': ['local', 'public', 'administrator'], 'userA': ['local'], 'userB': ['public']}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python