首页 > 解决方案 > 根据另一个 dict 值对 dict 进行排序

问题描述

我有两个这样的字典:

dict1={'key10': {'fail_pass': 1, 'score': 29.5}, 'key20': {'fail_pass': 0, 'score': 37.25}, 'key30': {'fail_pass': 0, 'score': 25.75}, 'key60': {'fail_pass': 1, 'score': 225.75}, 'key70': {'fail_pass': 1, 'score': 25.25}, 'key170': {'fail_pass': 1, 'score': 0.25}}
dict2={'key10': 1, 'key20': 1, 'key60': 1}

我想根据 dict1 对 dict2 进行排序score。所以,在这种情况下,我想要返回这样排序的 dict2:

sorted_dict2={'key60': 1, 'key20': 1, 'key10': 1}

` 我如何实现这一目标?

标签: pythondictionary

解决方案


您可以使用sorted函数对字典进行排序并lambda访问要排序的参数:

dict1={'key10': {'fail_pass': 1, 'score': 29.5}, 'key20': {'fail_pass': 0, 'score': 37.25}, 'key30': {'fail_pass': 0, 'score': 25.75}, 'key60': {'fail_pass': 1, 'score': 225.75}, 'key70': {'fail_pass': 1, 'score': 25.25}, 'key170': {'fail_pass': 1, 'score': 0.25}}
dict2={'key10': 1, 'key20': 1, 'key60': 1}

sortedDict = dict(sorted(dict2.items(), key=lambda x: dict1[x[0]]['score'], reverse=True))

print(sortedDict)

推荐阅读