Vaibhav Bhavsar Vaibhav Bhavsar - 1 month ago 9
PHP Question

How can I write this in Python?


I have developed a script where I want to write this php code in python.

How can I create a this
array in python?

So far I have done this:

categories_c.insert(row["category_parent_id"], row)

But I am not sure if this is the correct implementation.


Let's deconstruct:


This accesses the categories property of the $class object. In Python that's:

klass.categories  # (class is a reserved keyword, using klass instead)

We'll assume that categories is a dict here, because you want to do this:


This accesses a particular key of an array, in Python that would be the key of a dict:


Now the tricky part:

...[] = $cat

This pushes $cat into the array. In Python that means appending a value to a list. PHP will implicitly create new sub-arrays as necessary if they don't exist. Python doesn't. This is the only part that needs a bit of additional consideration. What you need to know is whether categories[cat.category_parent_id] already exists in your dict or whether you want to create it in the process.

If you know it exists, if categories is a dict of lists in which all cat.category_parent_id keys are already pre-populated, then it's as simple as this:


However, if the keys don't exist, you must ensure they're created and that their value is set to a list the first time they're accessed. The most compact notation for that in Python is the dict.setdefault method:

klass.categories.setdefault(cat.category_parent_id, []).append(cat)

If categories[cat.category_parent_id] exists, it is returned and you can append to it. If it doesn't exist, it is created and initialised to [] and then returned.