python - 根据另一个 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}
` 我如何实现这一目标?
解决方案
您可以使用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)
推荐阅读
- model-view-controller - 使用 VS 的 MVC:为什么在使用 View() 时出现错误,但在使用 View(viewname) 时却没有?
- python - 为什么 img[0:overlap,:,:] = 1 工作,但在 numpy 但不是 img = img[0:overlap,:,:] = 1 没有?
- sql - 如何确定 Oracle ORA_Hash 函数的最佳 Max_bucket 和 Seed_value?
- asp.net - 为什么我的注册表有效而我的登录表格无效
- avr - 如何以编程方式识别连接到我的计算机的微控制器
- c# - 带有异步 lambda 的 Parallel.ForEach 等待所有迭代完成
- java - 在 Netty 中解码和编码多种数据包类型
- php - AJAX GET & POST 方法在 Laravel 中不起作用。显示错误
- javascript - 如何将包含自然值和货币的字段相乘?
- flutter - 即使我测试了数据是正确的,Flutter Provider 也没有更新我的 Widget?