2 回答

TA貢獻(xiàn)1847條經(jīng)驗(yàn) 獲得超7個(gè)贊
也許嘗試一個(gè)功能?
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
該函數(shù)返回,
filter_dict(1,5,my_dict)
{'user_1': {'role': 1, 'perm': 5}, 'user_2': {'role': 1, 'perm': 5}}

TA貢獻(xiàn)1807條經(jīng)驗(yàn) 獲得超9個(gè)贊
當(dāng)你建立索引時(shí),你有點(diǎn)想把整個(gè)事情翻個(gè)底朝天。然后你可以使用索引來(lái)構(gòu)造你想要的字典:
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))
結(jié)果:
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
}
}
添加回答
舉報(bào)