2 回答
TA贡献1777条经验 获得超3个赞
您可以迭代当前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']}
TA贡献1786条经验 获得超11个赞
请尝试下面的程序。它只是迭代 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']}
添加回答
举报