用另一本字典对字典排序


问题内容

我在用字典制作排序列表时遇到了问题。我有这个清单

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.
]

我试图遍历列表,

  • 从每个词典中创建一个包含该词典中项目的新列表。( 随着用户做出选择,它会改变哪些项目以及需要添加到列表中的项目的数量
  • 排序列表

当我说排序时,我想像这样创建一个新字典

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']
['thatfile.flt', 'teapot', '6.0', '12.4', '3.0']

另一方面,它们可能看起来像这样

['thisfile.flt', 'box', '8.7', '10.5', 'red.jpg']
['thatfile.flt', 'teapot', '6.0', '12.4', 'blue.jpg']

我想我的问题是,我将如何根据字典中的特定值制作一个列表,然后将其与另一个具有与第一个字典相同键的字典中的值排序?

感谢任何想法/建议,对不起的行为-我仍在学习python /编程


问题答案:

第一个代码框具有无效的Python语法(我怀疑这些d =部分是多余的??)以及对内置名称的不明智践踏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']方法是:

def doit(d, order):
  return  [d[k] for k in sorted(order, key=order.get)]