python - 如何在字典中修改?
问题描述
groups_per_user 函数接收一个字典,其中包含组名和用户列表。用户可以属于多个组。填空返回一个字典,其中用户作为键,他们的组列表作为值
def groups_per_user(group_dictionary):
user_groups = {}
# Go through group_dictionary
for ___:
# Now go through the users in the group
for ___:
# Now add the group to the list of
# groups for this user, creating the entry
# in the dictionary if necessary
return(user_groups)
print(groups_per_user({"local": ["admin", "userA"],
"public": ["admin", "userB"],
"administrator": ["admin"] }))
解决方案
def groups_per_user(group_dictionary):
user_groups = {}
# Go through group_dictionary
for group in group_dictionary:
# Now go through the users in the group
for user in group_dictionary[group]:
try:
user_groups[user].append(group)
except KeyError:
user_groups[user] = [group]
# Now add the group to the list of
# groups for this user, creating the entry
# in the dictionary if necessary
return(user_groups)
推荐阅读
- c# - 如何使用名称从 bsondocument 中删除子元素?
- python-3.7 - 在python的for循环中使用Ax = b中的先前值x(i-1)获取x(i)数组很热
- mysql - MySQL Max() 与 group by 和多个表
- r - 手动设置 hoverinfo 文本
- javascript - 代码使用静态 PHP 值但不是动态变量
- regex - 具有 ISO 货币和字符串匹配的正则表达式
- microsoft-graph-api - 为什么我们突然在图表调用上得到 403 来列出团队的频道?
- javascript - Javascript函数正在脱离上下文更改变量
- bash - 无法有条件地执行脚本
- excel - 多个条件if语句检查三个值之一,如果不是三个值之一,则替换值?