按另一本词典对词典进行排序

2024-06-10 01:01:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直有一个问题,从字典整理清单。 我有这个单子

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

我试着循环查看列表

  • 从每个字典创建一个新列表,其中包含字典中的项。(当用户做出选择时,需要将哪些项和多少项附加到列表中
  • 对列表排序

当我说sort的时候,我想象着创建一个像这样的新字典

^{pr2}$

它根据order字典中的值对每个列表进行排序。在


在脚本的一次执行过程中,所有列表都可能如下所示

['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/编程


Tags: namebox列表字典排序itemwidthfile
1条回答
网友
1楼 · 发布于 2024-06-10 01:01:51

第一个代码框有无效的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
}

获得所需结果的一种好方法是:

^{pr2}$

相关问题 更多 >