按另一个字典排序字典

7 投票
1 回答
6360 浏览
提问于 2025-04-15 13:29

我在从字典中制作排序列表时遇到了一些问题。
我有这样一个列表:

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/编程。

1 个回答

12

第一个代码块的语法在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)]

撰写回答