Answer the question
In order to leave comments, you need to log in
Translation of code from php to python?
Good morning, I'm translating php code into python here, please help with one problem.
Here is the php code
class Test {
private $data = [];
public function unit()
{
foreach ($data as $row)
{
$id = rand();
$this->data[$data[0]][$data[1]][$data[2]] = [
'name' => $data[2],
'id' => $id
];
}
$this->sortAscAll();
}
private function sortAsc($a, $b)
{
if ($a['id'] == $b['id']) {
return 0;
}
return ($a['id'] < $b['id']) ? -1 : 1;
}
public function sortAscAll()
{
foreach ($this->data as $oneID => $In)
{
foreach ($In as $twoId => $item) {
uasort($item, [$this, 'sortAsc']);
$this->data[$oneID][$twoId] = $item;
}
}
return $this;
}
}
class Test:
__data = dict()
def unit(self):
self.__data = AutoVivification()
for item in read:
self.__data[data[0]][data[1]][data[2]] = (
'name', data[2],
'id', rand
)
self.__sortAscAll()
def __sortAscAll(self):
for oneID, In in self.__data.items():
for twoID, item in In.items():
# Никак не могу сортировать по ключу id
sorted(item.items(), key=lambda tuple: print(tuple), reverse=True)
self.__data[oneID][twoID] = item
class AutoVivification(dict):
def __getitem__(self, item):
try:
return dict.__getitem__(self, item)
except KeyError:
value = self[item] = type(self)()
return value
Answer the question
In order to leave comments, you need to log in
If you have a list (list) of dictionaries (dict), then to sort it inplace you can write like this:
list_of_dicts = item.items()
list_of_dicts.sort(key=lambda x: x['id'])
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question