我有一个这样的词典,每个用户或每个群组拥有不同的权限:
"permissions": [
{
"user": 4,
"type": "admin"
},
{
"user": 3,
"type": "read"
},
{
"group": 3,
"type": "admin"
}
]
按权限类型获取分组的最有效方法是什么:
数字表示对象(用户/组)的ID,所以我还必须在结果中“翻译”它们:
"permissions": [
{
"type": "admin",
"users":[
{"id":4}
],
"groups":[
{"id":3}
]
},
{
"type": "read",
"users":[
{"id":3}
]
},
]
感谢您的帮助!
答案 0 :(得分:0)
为了回答我自己的问题,我找到了以下解决方案:
我的代码,没有任何智能,只需简单的迭代。在第一次运行中,我创建了一个中间字典,按权限类型分组:
permissions_bytype={}
for permission_entry in permissions: #iterating over something like: [{'user': 1, 'type': u'read'}, {'user': 4, 'type': u'admin'}, {'user': 4, 'type': u'read'}]
if permission_entry["type"] not in permissions_bytype:
permissions_bytype[permission_entry["type"]] = {}
for key,val in permission_entry.iteritems():
if key <> "type": #is user or group
if key not in permissions_bytype[permission_entry["type"]]:
permissions_bytype[permission_entry["type"]][key] = []
permissions_bytype[permission_entry["type"]][key].append({"id":val})
然后构建结果:
result=[]
for perm_type,permission_value in permissions_bytype.iteritems():
permission_value["type"] = perm_type
result.append(permission_value)