我有一个包含以下信息的字典:
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'.
答案 0 :(得分:4)
只需按值排序dictionary items :
>>> 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'.