用另一本字典对字典排序 [英] sort dictionary by another dictionary
问题描述
我在用字典制作排序列表时遇到了问题. 我有这个清单
I've been having a problem with making sorted lists from dictionaries. I have this list
list = [
d = {'file_name':'thisfile.flt', 'item_name':'box', 'item_height':'8.7', 'item_width':'10.5', 'item_depth':'2.2', 'texture_file': 'red.jpg'},
d = {'file_name':'thatfile.flt', 'item_name':'teapot', 'item_height':'6.0', 'item_width':'12.4', 'item_depth':'3.0' 'texture_file': 'blue.jpg'},
etc.
]
我试图遍历列表,然后
- 从每个字典中创建一个新列表,其中包含该字典中的项目. (随着用户做出选择,它会改变哪些项目以及需要添加到列表中的项目)
- 对列表进行排序
我说排序的时候,我想像这样创建一个新字典
When I say sort, I imagine creating a new dictionary like this
order = {
'file_name': 0,
'item_name': 1,
'item_height': 2,
'item_width': 3,
'item_depth': 4,
'texture_file': 5
}
,并按顺序字典中的值对每个列表进行排序.
and it sorts each list by the values in the order dictionary.
在执行脚本的过程中,所有列表看起来都像这样
During one execution of the script all the lists might look like this
['thisfile.flt', 'box', '8.7', '10.5', '2.2']
['thatfile.flt', 'teapot', '6.0', '12.4', '3.0']
另一方面,它们可能看起来像这样
on the other hand they might look like this
['thisfile.flt', 'box', '8.7', '10.5', 'red.jpg']
['thatfile.flt', 'teapot', '6.0', '12.4', 'blue.jpg']
我想我的问题是,我将如何根据字典中的特定值创建一个列表,然后将其与另一个具有与第一个字典相同键的字典中的值进行排序?
I guess my question is how would I go about making a list from specific values from a dictionary and sorting it by the values in another dictionary which has the same keys as the first dictionary?
感谢任何想法/建议,对不起的行为表示抱歉-我仍在学习python/编程
Appreciate any ideas/suggestions, sorry for noobish behaviour - I am still learning python/programming
推荐答案
第一个代码框的Python语法无效(我怀疑d =
部分是多余的...?),并且不明智地践踏了内置代码名称list
.
The first code box has invalid Python syntax (I suspect the d =
parts are extraneous...?) as well as unwisely trampling on the built-in name list
.
反正,例如:
d = {'file_name':'thisfile.flt', 'item_name':'box', 'item_height':'8.7',
'item_width':'10.5', 'item_depth':'2.2', 'texture_file': 'red.jpg'}
order = {
'file_name': 0,
'item_name': 1,
'item_height': 2,
'item_width': 3,
'item_depth': 4,
'texture_file': 5
}
获得所需结果['thisfile.flt', 'box', '8.7', '10.5', '2.2', "red.jpg']
的一种巧妙方法是:
one nifty way to get the desired result ['thisfile.flt', 'box', '8.7', '10.5', '2.2', "red.jpg']
would be:
def doit(d, order):
return [d[k] for k in sorted(order, key=order.get)]
这篇关于用另一本字典对字典排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!