简体   繁体   English

python-基于字典值的字典顺序列表

[英]python - order list of dict based on dict values

Lets consider the following list of dicts: 让我们考虑以下字典列表:
ins=[dict(rank=1, data="Pierre"),dict(rank=3, data="Paul"),dict(rank=2,data="Jacques")]

How can I convert it to the following list: ["Pierre", "Jacques", "Paul"] 如何将其转换为以下列表: ["Pierre", "Jacques", "Paul"]

that is reordering the items with the rank key and only keeping the data key items? 那就是用rank键重新排列项目,只保留data键项目?

You can do it fairly easily with comprehensions and the sorted() function's key parameter: 您可以通过理解和sorted()函数的key参数轻松地做到这一点:

ranked_data = [d['data'] for d in sorted(ins, key=lambda x: x['rank'])]

(You can also use operators.itemgetter('rank') instead of the lambda function, but the lambda is easier to use as an example here.) (您也可以使用operators.itemgetter('rank')代替lambda函数,但是在这里lambda易于用作示例。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM