2015-09-27 43 views
1

我有一个包含以下信息的字典:排序打印输出列表的字典,按字母顺序排列的列表的索引0

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

回答

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

Hey alecxe!一个问题:为什么你在itemgetter()中使用1? –

+0

@JuandelaCruz这是因为'items()'会给你第一个元素(有0个索引)是关键字,第二个(有索引1)是一个值的元组。这样我们要求'sorted()'使用字典值作为排序键。另见:http://stackoverflow.com/questions/613183/sort-a-python-dictionary-by-value。希望有所帮助。 – alecxe

+0

非常感谢!这非常有帮助! –