python - 按另一个字典排序字典

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

最佳答案

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

关于python - 按另一个字典排序字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1252481/

相关文章:

python - 基于多列对 numpy 文本数组中包含数字的列进行排序

javascript - 数据表 API : Datatables can't sort a column of integers due to the render (which inserts a string in certain elements)

c# - 在 Linq 中查找正则表达式匹配的索引

c++ - 在 map C++ 中使用数组作为键

Python 请求模块和 JSON 响应

python - 从 NLTK 中训练新的斯坦福词性标注器

python - GTK如何添加标签项子项

python - 使用 python 中的 readline() 读取特定行

c - 对数组中的 2 个字符串进行排序并将它们合并为 C 中的一个

java - HashMap Java 如果存在则获取值