[英]How to sort array based dictionary in Python
I have data that has been arranged in the following format我有按以下格式排列的数据
products{} = {'001':['001','Espreso',2.50],
'002':['002', 'Latte',1.50],
'003':['003', 'Orange Juice',1.00],
'004':['003', 'Apple Juice',1.00],
}
I would like to sort the dictionary based on price so that I can get the following output.我想根据价格对字典进行排序,以便获得以下输出。
products{} = {'003':['003', 'Orange Juice',1.00],
'004':['003', 'Apple Juice',1.00],
'002':['002', 'Latte',1.50],
'001':['001','Espreso',2.50],
}
Being a newbie to python, I cant seem to find a proper guidance to sort this.作为 Python 的新手,我似乎找不到合适的指导来对此进行排序。 I have an array as value.
我有一个数组作为值。
Please guide how to achiece this?请指导如何实现这一点? Is this even a correct way of assigning array as value to a key.?
这甚至是将数组作为值分配给键的正确方法。? Is this known as ordered dictionary?
这被称为有序字典吗?
To sort dictionary you can pass it's items into a sorted()
and initialize new dictionary from sorted key-value pairs.要对字典进行排序,您可以将其项传递到
sorted()
并从排序的键值对初始化新字典。
To sort items of your dictionary by last element of value, we should pass to key
argument of sorted()
a lambda
which will return receive key-value pair and return last element ( -1
index) of value ( 1
index) .要按值的最后一个元素对字典的项目进行排序,我们应该将一个
lambda
传递给sorted()
的key
参数,它将返回接收键值对并返回值( 1
索引)的最后一个元素( -1
索引) 。
Code:代码:
products = {
'001':['001','Espreso',2.50],
'002':['002', 'Latte',1.50],
'003':['003', 'Orange Juice',1.00],
'004':['003', 'Apple Juice',1.00]
}
sorted_products = dict(sorted(products.items(), key=lambda x: x[1][-1]))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.