python - 从按字母顺序排列的列表的索引为 0 的列表字典中对打印输出进行排序

标签 python list sorting python-3.x dictionary

我有一本包含以下信息的字典:

my_dict = {
'key1' : ['f', 'g', 'h', 'i', 'j'],
'key2' : ['b', 'a', 'e', 'f', 'k'],
'key3' : ['a', 'd', 'c' , 't', 'z'],
'key4' : ['a', 'b', 'c', 'd', 'e']
}

我想知道如何使用列表的索引 0 按字母顺序对打印结果进行排序。如果两个列表的索引 0 相同,它将在排序时考虑下一个索引为索引 1。

输出应该是这样的:

Officer 'a', 'b' with 'key4' ate 'c' with 'd' and 'e'.
Officer 'a', 'd' with 'key3' ate 'c' with 't' and 'z'.
Officer 'b', 'a' with 'key2' ate 'e' with 'f' and 'k'.
Officer 'f', 'g' with 'key1' ate 'h' with 'i' and 'j'.

最佳答案

只需dictionary items 进行排序按值(value):

>>> import operator
>>>
>>> for key, value in sorted(my_dict.items(), key=operator.itemgetter(1)):
...     print("Officer '{1}', '{2}' with '{0}' ate '{3}' with '{4}' and '{5}'.".format(key, *value))
... 
Officer 'a', 'b' with 'key4' ate 'c' with 'd' and 'e'.
Officer 'a', 'd' with 'key3' ate 'c' with 't' and 'z'.
Officer 'b', 'a' with 'key2' ate 'e' with 'f' and 'k'.
Officer 'f', 'g' with 'key1' ate 'h' with 'i' and 'j'.

关于python - 从按字母顺序排列的列表的索引为 0 的列表字典中对打印输出进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32803479/

相关文章:

python - matplotlib 中默认的随机颜色

python - 使用 countvectorizer() 和 tfidfvectorizer() 向量化列表列表

python - 在 Python 中使用自定义顺序对列表进行排序

java - 反向排序流

MySQL ORDER BY FIELD with %

python - 使用 Python 更改环境变量

Python - gcode 修饰符的 if 语句中存在多个 "or"条件问题

c# - 如何查看存储在列表中的值?

Python 计算唯一列表排列可能性

c++ - 将 std::sort 替换为 boost::sort