Python 按数字对字典列表进行排序

标签 python list sorting dictionary

我有一个要排序的字典列表。这是我目前所拥有的:

output_list = [{'interface': '0/20', 'mac': '01:23:45:67:89:AB'},
               {'interface': '0/16', 'mac': '12:34:56:78:9A:BC'},
               {'interface': '0/31', 'mac': '23:45:67:89:AB:CD'},
               {'interface': '0/5', 'mac': '34:56:78:9A:BC:DE'},
               {'interface': '0/3', 'mac': '45:67:89:AB:CD:EF'}]

mac_list = sorted(output_list, key=lambda d: d['interface'])

pprint(mac_list)

但是,它并没有按照我想要的方式对字典进行排序。

"C:\Program Files\Python310\python.exe" "C:/Scripts/Python/test1.py"
[{'interface': '0/16', 'mac': '12:34:56:78:9A:BC'},
 {'interface': '0/20', 'mac': '01:23:45:67:89:AB'},
 {'interface': '0/3', 'mac': '45:67:89:AB:CD:EF'},
 {'interface': '0/31', 'mac': '23:45:67:89:AB:CD'},
 {'interface': '0/5', 'mac': '34:56:78:9A:BC:DE'}]

Process finished with exit code 0

我怎样才能让它看起来像这样:

[{'interface': '0/3', 'mac': '45:67:89:AB:CD:EF'},
 {'interface': '0/5', 'mac': '34:56:78:9A:BC:DE'},
 {'interface': '0/16', 'mac': '12:34:56:78:9A:BC'},
 {'interface': '0/20', 'mac': '01:23:45:67:89:AB'},
 {'interface': '0/31', 'mac': '23:45:67:89:AB:CD'}]

最佳答案

您需要从字符串中获取数字:

sorted(output_list, key=lambda d: int(d['interface'].split("/")[1]))

这假设界面的第一部分不会改变。

如果它发生变化,您需要用前导零重新格式化这两个部分:

sorted(output_list, key=lambda d: "/".join([f"{int(x):02d}" for x in d['interface'].split("/")]))

关于Python 按数字对字典列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72715375/

相关文章:

python - 在 python 中别名 str.join

python - 元组作为单例的实际使用

list - 标准 Haskell 函数::(a -> Maybe a) -> a -> [a]

python - 从字符串列表中删除整数

r - 将环境中的所有 ggplot2 图存储在列表中

r - dplyr::summarize_at – 按传递的变量顺序对列排序,然后按应用函数的顺序排序

python - 使用 Pandas 在多个工作表中查找最小值

python - 如何仅使用 c/python api 将 c++ 成员函数绑定(bind)到 python?

PHP 按第二个数组排序 array_intersect_key() 结果

python - 在Python中降序排序字典