How to name the indexes of an array of arrays according to another array?

Asked

Viewed 203 times

-3

Having the following array of arrays

array1=[indice1[1,2,3], indice2[4,5,6]]

and the second

array2=['nome1','nome2']

How to make the first array (array of arrays = array1) have the same names in its second array indices?

Thus:

print(array1)


[nome1[1,2,3], nome2[4,5,6]]
  • 1

    has something wrong with this syntax in array1=[indice1[1,2,3], indice2[4,5,6]]

1 answer

1

It is not possible to "name" lists because they only work with positions. What you may be looking for is called dictionary, which is an object in which it has a key and a value.

Using dictionaries, you can define a "name" (key) for your lists (value) and get each value through their respective keys. See below how it would look:

dicionario = {"indice1": [1, 2, 3], "indice2": [4, 5, 6]}

dicionario["indice1"] # Retorna: [1, 2, 3]
  • What if I have a dictionary like this: dados = {"indice1": [1, 2, 3], "indice2": [4, 5, 6]} , and you want to name the indexes with the following array: names= ['nome1', 'nome2'] I can do like this: dados.keys()=names ???

  • First of all, the keys() is not an attribute but a method, so it is not possible to make that syntax you want. Now, what you mean by naming indexes with an array ?

  • If what you mean is to turn a list into a key, no, this is not possible because the only values you can use as keys are primitive types (string, int, float, bool).

  • If you want to turn the elements inside the list names in keys, yes it is possible and you can do it by going through the list with a for loop and always adding a value to the key, that way: for name in names: dic[name] = None.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.