Reputation: 5152
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"]
that is reordering the items with the rank
key and only keeping the data
key items?
Upvotes: 0
Views: 353
Reputation: 527508
You can do it fairly easily with comprehensions and the sorted()
function's key
parameter:
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.)
Upvotes: 2