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.
CodePudding user response:
You can use key
parameter:
dct = {"A1":"value1", "C1":"value3", "B1":"value2", "C2":"value6", "A2":"value4", "B2":"value5"}
output = dict(sorted(dct.items(), key=itemgetter(1)))
# alternatively: output = dict(sorted(dct.items(), key=lambda x: x[1]))
print(output) # {'A1': 'value1', 'B1': 'value2', 'C1': 'value3', 'A2': 'value4', 'B2': 'value5', 'C2': 'value6'}
Note that this dictionary "sorting" is only guaranteed for python 3.7 .
CodePudding user response:
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'}