我有一本包含以下信息的字典:
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/