I'm creating a dictionary where the keys should be the row number and the values should be a list of values of that row, sorted in descending order. I'm unsure how to change the keys to row number.
My code below is:
from openpyxl import load_workbook
vWB = load_workbook(filename="voting.xlsx")
vSheet = vWB.active
dictionary = {
row[0].value: [cell.value for cell in row[0:]]
for row in vSheet.rows
}
print(dictionary)
output:
{0.296177589742431: [0.296177589742431, 0.434362232763003, 0.0330331941352554, 0.758968208500514], 0.559322784244604: [0.559322784244604, 0.455791535747786, 0.770423104229537, 0.770423104229537], 0.590959914883228: [0.590959914883228, 0.51958013385644, 0.731606088347655, 0.76747303738125], 0.555107939188315: [0.555107939188315, 0.34428487590259, 0.543483969378315, 0.396020990933073], 0.836279279852424: [0.836279279852424, 0.950927663854436, 0.871995522067921, 0.852851115576947], 0.793427229667316: [0.793427229667316, 1.50914812927441, 0.700621254351196, 0.65930621574405]}
What I want:
{1: [0.758968208500514, 0.434362232763003, 0.296177589742431, 0.0330331941352554], 2: [0.770423104229537, 0.770423104229537, 0.559322784244604, 0.455791535747786], 3: [0.76747303738125, 0.731606088347655, 0.590959914883228, 0.51958013385644], 4: [0.555107939188315, 0.543483969378315, 0.396020990933073, 0.34428487590259], 5: [0.950927663854436, 0.871995522067921, 0.852851115576947, 0.836279279852424], 6: [1.50914812927441, 0.793427229667316, 0.700621254351196, 0.65930621574405]}
How do I change the keys to row number not row value and how do I sort the dictionary values of each list in descending order. Many thanks for your help!
CodePudding user response:
Simply use enumerate:
dictionary = {
row_id: [cell.value for cell in row]
for row_id, row in enumerate(vSheet.rows)
}
enumerate can be applied to iterables and returns an iterator over a tuple of index and value. For example:
x = ['a', 'b', 'c']
print(list(enumerate(x)))
yields [("a", 0), ("b", 1), ("c", 2)].
If you want to start with 1, then use enumerate(x, 1).
CodePudding user response:
You can use enumerate
dictionary = {
i: [cell.value for cell in row[0:]]
for i, row in enumerate(vSheet.rows)
}
