2 回答

TA貢獻(xiàn)1777條經(jīng)驗(yàn) 獲得超3個(gè)贊
您可以迭代當(dāng)前dict并反轉(zhuǎn)鍵值對(duì):
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貢獻(xiàn)1786條經(jīng)驗(yàn) 獲得超11個(gè)贊
請(qǐng)嘗試下面的程序。它只是迭代 group_dictionary 的所有元素并構(gòu)造 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']}
添加回答
舉報(bào)