Python:按关键字nam排序字典中的列表

2024-05-17 18:56:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个字典对象如下:

{'Role Name': ['Administrator'], 'Approval': ['N', 'N', 'N', 'N', 'N'], 'Functions': ['Transfer Amount', 'Withdraw Amount', 'Admin Action', 'Create Users', 'User Deletion'], 'Approve': ['N', 'Y', 'N', 'N', 'N'], 'Action': ['N', 'Y', 'Y', 'Y', 'Y']}

我想按函数排序,这样相应的审批、审批和操作也应该分别排序。显示以下示例:

^{pr2}$

有人能给我指路吗?在


Tags: 对象name字典admin排序createactionfunctions
2条回答

您需要根据'Functions'的顺序对其他列表进行排序,并将该列表排序到最后。实现这一点的一种方法是使用^{}'Functions'和{}组合成一个列表[('Transfer Amount', 'N'), ...],对其进行排序,然后从每个对中提取第二个值(例如使用^{}^{}):

from operator import itemgetter

data = {'Role Name': ['Administrator'], 
        'Approval': ['N', 'N', 'N', 'N', 'N'], 
        'Functions': ['Transfer Amount', 'Withdraw Amount', 'Admin Action', 'Create Users', 'User Deletion'], 
        'Approve': ['N', 'Y', 'N', 'N', 'N'], 
        'Action': ['N', 'Y', 'Y', 'Y', 'Y']}

for key in ['Action', 'Approval', 'Approve']:
    data[key] = map(itemgetter(1), sorted(zip(data['Functions'], data[key])))

data['Functions'] = sorted(data['Functions'])

这给了我你想要的答案:

^{pr2}$

下面是一个解决方案: 我通过使用这个技术to get indices of a sorted list删除了numpy依赖项 我们找到排列的索引来对'Functions'进行排序,然后将这个置换应用于除'Role Name'之外的所有密钥:

dictionary = {'Role Name': ['Administrator'],
 'Approval': ['N', 'N', 'N', 'N', 'N'],
 'Functions': ['Transfer Amount', 'Withdraw Amount', 'Admin Action', 'Create Users', 'User Deletion'],
 'Approve': ['N', 'Y', 'N', 'N', 'N'],
 'Action': ['N', 'Y', 'Y', 'Y', 'Y']}

sorted_idx = sorted(range(len(dictionary['Functions'])), key=lambda k: dictionary['Functions'][k])
for key in dictionary:
    if not (key == 'Role Name'):
        dictionary[key] = [dictionary[key][idx] for idx in sorted_idx]

它回来了

^{pr2}$

相关问题 更多 >