Skip to content
Advertisement

Python regex function to arrange key:value in descending order. Wherein the key is alphanumeric and the value is digits

Say I have a column which has values like:

JavaScript

I would like the piece of code that I am working on to return:

JavaScript

I’m trying to get the code to sort this key-value pair based on the value of the item in descending order This is the code I have written as of now, but it’s sorting based on the digits in the Key and not the value.

JavaScript

The code outputs:

JavaScript

Which is not the expected output. Please help with the corrections in the code required to achieve the desired output. Thank you.

Advertisement

Answer

You may use

JavaScript

Pandas test:

JavaScript

NOTES:

  • r.split(', ') – splits each cell value with comma+space
  • sorted(..., key=lambda s: int(s.split(':')[-1]), reverse=True) – sorts the split chunks by the integer value that is after : (obtained by splitting the cell value with : and last item accessed with [-1] and then cast to int using int(s.split(':')[-1])) in descending order (due to reverse=True
  • ', '.join(...) – combines back the split chunks
Advertisement