将列表的索引为0的列表字典的打印输出按字母顺序排序

2024-04-24 09:27:25 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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'.

Tags: and信息列表排序mywith字母dict
1条回答
网友
1楼 · 发布于 2024-04-24 09:27:25

只需对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'.

相关问题 更多 >