Thursday, 15 March 2012

Python dictionary group by a field -



Python dictionary group by a field -

this question has reply here:

get key value in dictionary 22 answers

i have dictionary different permissions per users or per groups:

"permissions": [ { "user": 4, "type": "admin" }, { "user": 3, "type": "read" }, { "group": 3, "type": "admin" } ]

what efficient way obtain grouping permission type:

the numbers represent id of objects(users/groups) have "translate" them little bit in result:

"permissions": [ { "type": "admin", "users":[ {"id":4} ], "groups":[ {"id":3} ] }, { "type": "read", "users":[ {"id":3} ] }, ]

thanks helping !

to reply own question, i've found next solution:

my code, nil smart, simple iterations. in first run create intermediary dictionary,grouping permission type:

permissions_bytype={} permission_entry in permissions: #iterating on 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"]] = {} key,val in permission_entry.iteritems(): if key <> "type": #is user or grouping if key not in permissions_bytype[permission_entry["type"]]: permissions_bytype[permission_entry["type"]][key] = [] permissions_bytype[permission_entry["type"]][key].append({"id":val})

then build result:

result=[] perm_type,permission_value in permissions_bytype.iteritems(): permission_value["type"] = perm_type result.append(permission_value)

python dictionary grouping

No comments:

Post a Comment