sort string with number python dictionary

Question:

I have a python dictionary like this:

dict = {"A1":"value1", "C1":"value3", "B1":"value2", "C2":"value6", "A2":"value4", "B2":"value5"}

(actually, keys are Excel cells address)

and I want to sort the dictionary like this:

sorted_dict = {"A1":"value1", "B1":"value2", "C1":"value3", "A2":"value4", "B2":"value5", "C2":"value6"}

can anybody help me?

thanks.

Asked By: ecopy

||

Answers:

Try this

dict_ = {"A1":"value1", "C1":"value3", "B1":"value2", "C2":"value6", "A2":"value4", "B2":"value5"}


d = {k:v for k,v in sorted(dict_.items(),key=lambda e:e[1])}


print(d) # {'A1': 'value1', 'B1': 'value2', 'C1': 'value3', 'A2': 'value4', 'B2': 'value5', 'C2': 'value6'}

Run code

Answered By: codester_09
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.