Hello! In PHP array can be written as follows:
$array[$index]['example'] = "My text"; How to crank up a similar operation in Python?
If I understand the question correctly, then this is not possible in Python. You must first create a container, and then add elements to it. In PHP, exactly the same thing happens, but the interpreter hides it from you. For your example, the container will most likely be a list or dictionary. Container will be - two. As an element of the first container - the second container. You also need to create it first, and then add elements to it.
There are several options to do what you want. The specific option depends on the problem being solved.
The simplest thing is to present your data structure as nested dictionaries.
Option 1.
some = dict() some[index] = dict() some['example'] = 'My text' Option 2. The same can be written more succinctly:
some = dict() some[index] = dict(example='My text') Option 3. As far as I understand, index is a number. In this case, it cannot be slipped as an argument to the dict() constructor. But you can use the letter form of dictionaries.
some = { index: { 'example': 'My text' } } Option 4. It's all good, but what to do if you still need a list, not a dictionary.
some = list() some += [dict(example='My text')] Here we have created a list, and put a dictionary as its first element. "Unfortunately", the lists are numbered from "0", and then in order. Those. you can not fill in the elements "5", "10", "25", and the rest do not fill, as in PHP or Perl.
If there is only one item in the list, you can shorten it:
some = [dict(example='My text')] Option 5. I would suggest to look towards the collections . Perhaps the original task will be better placed on methods from this module.
Option 6. If you implement a list of data of a complex structure, then it is more correct to do this with classes. So it will be easier to control what is happening.
array[index]['example'] = "My text" already be a sufficient answer (although it is not known what the author wants). One can guess for a long time what is needed: array = [{'example': 'My text'}] or array = vividict(); where vividict = lambda: collections.defaultdict(vividict) or array.append({'example': 'My text'}) or array[index] = d or something else - the word "impossible" should not be used, Moreover, we do not know the exact formulation of the problem. - jfsThe fact is that data types in different languages ​​use the same. The principles of working with them are also about the same.
Therefore, the answer will be: just like you wrote, only without a dollar sign .
Source: https://ru.stackoverflow.com/questions/661685/
All Articles
array[index]['example'] = "My text"- jfs