按另一个字典排序字典

时间:2009-08-09 22:26:26

标签: python sorting dictionary

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

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 个答案:

答案 0 :(得分:11)

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