N
N
Nubbin2018-03-06 10:12:25
PHP
Nubbin, 2018-03-06 10:12:25

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;
  }
}

I partially translated, but I can't translate the sorting.
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

Please help, I really need it, I can't do it for 2 days

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander, 2018-03-19
@Survtur

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'])

But I'm confused by item.items(). If this function returns not the original list itself, but its copy, then sorting will not change the original list. That is why I divided into two lines what would be quite readable in one line. Although if you have an item - a standard dict, then everything is ok.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question