Как отсортировать словарь списка по определенному столбцу? - PullRequest
3 голосов
/ 12 июля 2020

У меня есть таблица, как показано ниже, хранящаяся в словаре:

enter image description here

The dictionary looks like this

d = {
'A': ['45', '70', '5', '88', '93', '79', '87', '69'], 
'B': ['99', '18', '91', '3', '92', '2', '67', '15'], 
'C': ['199200128', '889172415', '221388292', '199200128', '889172415', '889172415', '199200128', '221388292'], 
'D': ['10:27:05', '07:10:29', '17:04:48', '10:25:42', '07:11:18', '07:11:37', '10:38:11', '17:08:55'], 
'E': ['73', '6', '95', '21', '29', '15', '99', '9']
}

I'd like to sort the dictionary based on the hours from lowest to highest and sum the columns A, B and E corresponding the same value in column C as in image below (where sums of A, B and E are in red):

enter image description here

Then, the resulting dictionary would look like this:

{
'A': ['70', '93', '79', '242', '88', '45', '133', '87', '5', '69', '161'], 
'B': ['18', '92', '2', '112', '3', '99', '102', '67', '91', '15', '173'], 
'C': ['889172415', '889172415', '889172415', '', '199200128', '199200128', '', '199200128', '221388292', '221388292', ''], 
'D': ['07:10:29', '07:11:18', '07:11:37', '', '10:25:42', '10:27:05', '', '10:38:11', '17:04:48', '17:08:55', ''], 
'E': ['6', '29', '15', '50', '21', '73', '94', '99', '95', '9', '203']
}

I currently try to sort the input dictionary with this code, but doesn´t seem to work for me.

>>> sorted(d.items(), key=lambda e: e[1][4])
[
('D', ['10:27:05', '07:10:29', '17:04:48', '10:25:42', '07:11:18', '07:11:37', '10:38:11', '17:08:55']), 
('E', ['73', '6', '95', '21', '29', '15', '99', '9']), 
('C', ['199200128', '889172415', '221388292', '199200128', '889172415', '889172415', '199200128', '221388292']), 
('B', ['99', '18', '91', '3', '92', '2', '67', '15']), 
('A', ['45', '70', '5', '88', '93', '79', '87', '69'])
]
>>>

Может кто-нибудь поможет с этим. Спасибо

1 Ответ

1 голос
/ 12 июля 2020

Разрешаете ли вы использовать pandas для решения этой задачи? Если да, то вы можете преобразовать свои данные в

pd.DataFrame 

объект

data = pd.DataFrame.from_dict(dictionary, orient = 'columns')
data = data.sort_values(by =„D”)

А затем снова вернуться в словарь, используя

_dict = data.to_dict() 
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...