按照另一个字典排序字典

7

我一直在使用字典制作排序列表时遇到问题。我有以下这个列表:

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
}

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

namedtuple类可能比字典更适合您在此处的目的。它在Python 2.6+的collections模块中,如果您使用的是2.4或2.5版本,请从Python Cookbook获取:http://code.activestate.com/recipes/500261/ - John Fouhy
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)]

1
啊,是的,我在发布之前编辑了太多次,变得有些马虎了。感谢您提供整洁的答案,否则我可能永远都想不出来。 - Ian
这不是我在2.6.2版本中得到的结果:
sorted((d[k] for k in order), key=order.get, reverse=True) ['8.7', 'box', 'thisfile.flt', 'red.jpg', '2.2', '10.5']
在3.0版本中,我遇到了一个错误:
sorted((d[k] for k in order), key=order.get, reverse=True Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unorderable types: NoneType() < NoneType()
- hughdbrown
该代码(http://github.com/hughdbrown/StackOverflow/blob/90c5ae8c79791bca550f5bfcb69fca1909e1f191/1252481.py)适用于Python 2.5和2.6.2,但无法在3.0上运行。当从命令行启动的Python 3.0会话中剪切并粘贴时,它可以运行。正在调查中... - hughdbrown
@hugh,这可能是换行符的问题——我在评论中没有看到任何换行符,SO的格式似乎也没有;你似乎正在使用字符串列表作为[d[k] ...]列表的索引,紧接着是['thisfile.flt', ...]。让我们去metaSO游说一下,争取找到一种在cmts中格式化代码的方法,但同时如果(现在看来很可能)你正在给出一个输出示例,你可以考虑省略它,在cmts中阅读代码已经够麻烦了,不需要额外的复杂性;-) - Alex Martelli
1
是的:在运行Python提示符命令的结果末尾的东西。当我发布它时,它看起来很好。是的,在注释中能够格式化代码会使生活变得更加简单。 - hughdbrown
显示剩余4条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接