[英]Python print the dictionary according to the first element in the dictionary value descending order
I have a dict likes this: 我有一个像这样的字典:
mydict = {
'Peter': [21, 2, 42.0],
'Kate': [15, 3, 45.0],
'Tom': [16, 6, 96.0],
'Lucy': [28, 4, 112.0],
}
The key is string,value is list. 关键是字符串,值是列表。 I want to print mydict according to the first element in the dictionary value descending order.
我想根据字典值降序的第一个元素打印mydict。
For example, I want this output: 例如,我想要此输出:
'Lucy',28,4,112.0
'Peter',21,2,42.0
'Tom',16,6,96.0
'Kate',15,3,45.0
How can I output such a result? 如何输出这样的结果?
You can iterate over the sorted result of dict.items
, and use str.join
: 您可以遍历
dict.items
的排序结果,并使用str.join
:
mydict = {
'Lucy': [28, 4, 112.0],
'Peter': [21, 2, 42.0],
'Kate': [15, 3, 45.0],
'Tom': [16, 6, 96.0]}
for a, b in sorted(mydict.items(), key=lambda x:x[-1][0] if isinstance(x, list) else x, reverse = True):
print('{},{}'.format(a, ','.join(map(str, b)) if isinstance(b, list) else b))
Output: 输出:
Lucy,28,4,112.0
Peter,21,2,42.0
Tom,16,6,96.0
Kate,15,3,45.0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.