NIS*_*AGA 2 python sorting dictionary python-3.x
我有两个 Python 字典 -
dict1 = {'a' : [1, 2, 3], 'b' : [4, 5, 6], 'c' : [7, 8, 9]}
dict2 = {'a' : 30, 'b' : 75, 'c' : 15}
Run Code Online (Sandbox Code Playgroud)
我想dict1根据 的值进行排序dict2。最终的答案应该是这样的——
[['c', [7, 8, 9]], ['a', [1, 2, 3]], ['b', [4, 5, 6]]]
Run Code Online (Sandbox Code Playgroud)
解决这个问题最有效的方法是什么?
是的。使用sorted()并传递一个“key”函数,该函数知道如何获取要排序的值。就像是:
sorted(dict1.items(), key=lambda kv: dict2[kv[0]])
Run Code Online (Sandbox Code Playgroud)
请注意,我将其保留为元组列表。如果您想要一个实际的字典,则必须使用 OrderedDict。
| 归档时间: |
|
| 查看次数: |
2841 次 |
| 最近记录: |