I have a column that contains dictionary like below
JavaScript
x
8
1
Column_1
2
{"X":5 , "Y" :10 , "Z" : 6}
3
{"X":0.4 , "Y": 0.1}
4
{"Z":0.55, "W": 7 , "X":3}
5
.
6
.
7
.
8
I need to write a Python code to sort each element in a column based on a value such as output will be like
JavaScript
1
8
1
Column_1
2
{"X":5 , "Z" : 6 ,"Y" :10 }
3
{"Y": 0.1, "X":0.4 }
4
{"Z":0.55, "X":3, "W": 7 }
5
.
6
.
7
.
8
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:
JavaScript
1
6
1
>>> Column_1
2
[{'X': 5, 'Y': 10, 'Z': 6}, {'X': 0.4, 'Y': 0.1}, {'Z': 0.55, 'W': 7, 'X': 3}]
3
>>> from operator import itemgetter
4
>>> [dict(sorted(mp.items(), key=itemgetter(1))) for mp in Column_1]
5
[{'X': 5, 'Z': 6, 'Y': 10}, {'Y': 0.1, 'X': 0.4}, {'Z': 0.55, 'X': 3, 'W': 7}]
6