I have a python dictionary like this:
dict = {"A1":"value1", "C1":"value3", "B1":"value2", "C2":"value6", "A2":"value4", "B2":"value5", "B10":"value7", "C10":"value8"}
(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",
"B10":"value7",
"C10":"value8"
}
can anybody help me?
thanks.
CodePudding user response:
first, dont name your variable with a reserved word dict
here, i sort first by the number, then letter A1
l = list(mydict.keys())
l.sort(key=lambda x: (int(x[1:]), x[0]))
mydict = {k: mydict[k] for k in l}
mydict
result:
{'A1': 'value1',
'B1': 'value2',
'C1': 'value3',
'A2': 'value4',
'B2': 'value5',
'C2': 'value6',
'B10': 'value7',
'C10': 'value8'}
CodePudding user response:
It looks as though the sort is based on the values in which case:
import re
data = {"A1":"value1", "C1":"value3", "B1":"value2", "C2":"value6", "A2":"value4", "B2":"value5", "B10":"value7", "C10":"value8"}
rep = re.compile('([A-Za-z]*)(\d )')
def cmp(x):
_, value = x
a, n = rep.findall(value)[0]
return int(n), a
print(dict(sorted(data.items(), key=cmp)))
Output:
{'A1': 'value1', 'B1': 'value2', 'C1': 'value3', 'A2': 'value4', 'B2': 'value5', 'C2': 'value6', 'B10': 'value7', 'C10': 'value8'}
Note:
The assumption here is that the values are a sequence of letters followed by a sequence of digits
CodePudding user response:
It looks like you want to sort by Excel row number and then column number, as derived from the cell address. To do that, you will need to convert the A1-style cell address into a sortable key. This is tricky because you can't just split or swap the alpha and numeric parts, since that won't handle columns like 'AA' correctly. Here is some code that should work, based on https://stackoverflow.com/a/12902801/3830997.
from openpyxl.utils.cell import coordinate_from_string, column_index_from_string
def row_col(item):
# item is a tuple of cell ref, value
coord = coordinate_from_string(item[0])
col = column_index_from_string(coord[0])
row = coord[1]
return (row, col)
my_dict = {"A1":"value1", "C1":"value3", "B1":"value2", "C2":"value6", "A2":"value4", "B2":"value5", "B10":"value7", "C10":"value8"}
new_dict = dict(sorted(my_dict.items(), key=row_col))
CodePudding user response:
For new output this will work
print(dict(sorted(dict_.items(), key=lambda x: x[1])))