2 回答
TA贡献1847条经验 获得超7个赞
也许尝试一个功能?
my_dict = {
'user_1': {'role': 1, 'perm': 5},
'user_2': {'role': 1, 'perm': 5},
'user_3': {'role': 1, 'perm': 4},
'user_4': {'role': 1, 'perm': 7},
'user_5': {'role': 3, 'perm': 5}
}
def filter_dict(role,perm,dic):
filtered = {}
users = [k for k in dic.keys() if dic[k]['role'] == int(role) and
dic[k]['perm'] == int(perm)]
for user in users:
filtered[user] = dic[user]
return filtered
该函数返回,
filter_dict(1,5,my_dict)
{'user_1': {'role': 1, 'perm': 5}, 'user_2': {'role': 1, 'perm': 5}}
TA贡献1807条经验 获得超9个赞
当你建立索引时,你有点想把整个事情翻个底朝天。然后你可以使用索引来构造你想要的字典:
import json
data = {
'user_1': {'role': 1, 'perm': 5},
'user_2': {'role': 1, 'perm': 5},
'user_3': {'role': 1, 'perm': 4},
'user_4': {'role': 1, 'perm': 7},
'user_5': {'role': 3, 'perm': 5}
}
# Build an index
index = {}
for (user, v) in data.items():
role = v['role']
perm = v['perm']
if role not in index:
index[role] = {}
if perm not in index[role]:
index[role][perm] = []
index[role][perm].append({user:v})
# Dump the index
# print(json.dumps(index, indent=4))
# Define our target dictionaries
repeated_role_perm = {}
only_role_repeated = {}
leftovers = {}
# Walk our index, putting each leaf into the right target dictionary
for role in index:
perms = index[role]
target = leftovers
for perm in perms:
users = index[role][perm]
if len(perms) > 1:
if len(users) > 1:
target = repeated_role_perm
else:
target = only_role_repeated
for userdict in users:
target.update(userdict)
# Print the results
print('repeated_role_perm = ' + json.dumps(repeated_role_perm, indent=4))
print()
print('only_role_repeated = ' + json.dumps(only_role_repeated, indent=4))
print()
print('leftovers = ' + json.dumps(leftovers, indent=4))
结果:
repeated_role_perm = {
"user_1": {
"role": 1,
"perm": 5
},
"user_2": {
"role": 1,
"perm": 5
}
}
only_role_repeated = {
"user_3": {
"role": 1,
"perm": 4
},
"user_4": {
"role": 1,
"perm": 7
}
}
leftovers = {
"user_5": {
"role": 3,
"perm": 5
}
}
添加回答
举报