Home > database >  How to order dictionary based column?
How to order dictionary based column?

Time:09-08

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!

CodePudding user response:

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}]

CodePudding user response:

My answer is assuming that the input is available as multi-line string obtained by printing, or read from a text file.

The explanation how it comes that the code is much longer compared to code in the other answer by Mechanic Pig is, that in spite of the fact I am using the same idea my approach does not rely on the order in which dictionary items are printed as this order is to my state of knowledge not guaranteed in Python. This requires own handling of the output.

The currently provided solution is still not perfect, because it can happen that it changes the formatting of the items/values. Maybe I will provide later on a better one.

dctTxt = """\
Column_1
{"X":5 , "Y" :10 , "Z" : 6}
{"X":0.4 , "Y": 0.1}
{"Z":0.55, "W": 7 , "X":3}"""
print(dctTxt)
print('---------------')
def sortDctTxtLine(dctTxtLine):
    from operator import itemgetter
    lstTpl = sorted( eval(dctTxtLine).items(), key=itemgetter(1) )
    tgtDctTxt = '{'   \
        ' , '.join( 
            (str(f'"{k}"') if isinstance(k, str) else str(k))   \
            ':'  str(v) for k, v in lstTpl )   '}'
    return tgtDctTxt
#:def
tgtTxt = '\n'.join( [ 
    line if line[0]!='{' else sortDctTxtLine(line) 
        for line in dctTxt.splitlines() ] )
print(tgtTxt)

gives:

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