Skip to content
Advertisement

How to order dictionary based column?

I have a column that contains dictionary like below

Column_1
{"X":5 , "Y" :10 , "Z" : 6}
{"X":0.4 , "Y": 0.1}
{"Z":0.55, "W": 7 , "X":3}
.
.
.

I need to write a Python code to sort each element in a column based on a value such as output will be like

Column_1
{"X":5 ,  "Z" : 6 ,"Y" :10 }
{"Y": 0.1, "X":0.4  }
{"Z":0.55, "X":3, "W": 7 }
.
.
.

Can someone help with that please?

I tried sorted function but it breaks at some point.

Thank you!

Advertisement

Answer

I assume that Column_1 is a list:

>>> Column_1
[{'X': 5, 'Y': 10, 'Z': 6}, {'X': 0.4, 'Y': 0.1}, {'Z': 0.55, 'W': 7, 'X': 3}]
>>> from operator import itemgetter
>>> [dict(sorted(mp.items(), key=itemgetter(1))) for mp in Column_1]
[{'X': 5, 'Z': 6, 'Y': 10}, {'Y': 0.1, 'X': 0.4}, {'Z': 0.55, 'X': 3, 'W': 7}]
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement