【问题标题】:sort dictionary by another dictionary按另一个字典排序字典
【发布时间】:2010-11-18 03:47:41
【问题描述】:

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

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

【问题讨论】:

  • namedtuple 类可能比这里的字典更适合您的目的。它位于 python 2.6+ 上的 collections 模块中,或者如果您使用的是 2.4 或 2.5,请从 Python Cookbook 获取它:code.activestate.com/recipes/500261

标签: python sorting dictionary


【解决方案1】:

第一个代码框的 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)]

【讨论】:

  • 啊,是的,我在发布之前重新编辑了太多次,变得草率了。感谢您的简洁回答,我从来没有想出来
  • 这不是我在 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(最近一次调用最后一次):文件“”,第 1 行,在 类型错误:不可排序的类型:NoneType()
  • 我可以在 2.5、2.6.2 和 3.0 中得到这个结果: >>> import operator >>> [d[k] for k,_ in sorted(order.items(), key=operator.itemgetter(1))] ['thisfile.flt', 'box', '8.7', '10.5', '2.2', 'red.jpg']
  • @hugh, tx 用于发现错误,我现在对其进行了编辑以修复它 - 但是您上一个 sn-p 中的代码没有运行(您正在使用字符串键寻址列表,所以当然不能运行)。
  • 是的:在 python 提示符下运行命令的结果末尾的东西。当我发布它时,它看起来不错。是的,能够在 cmets 中格式化代码会让生活变得简单得多。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-06-19
  • 1970-01-01
  • 2021-09-04
  • 1970-01-01
  • 1970-01-01
  • 2011-05-18
  • 2021-11-27
相关资源
最近更新 更多