Why are you giving the error string indices must be integers?

Asked

Viewed 629 times

-1

I’m a beginner in python

I’m trying to plot a graph by calling the function:

def plota_grafico(sistema, resultado, r, variavel)

As I have few variables I have created blocks of if depending on the choice of the variable. They all work correctly except the following block:

  if variavel == 'CMO':
for i, iusi in enumerate(resultado["DGer"]):
  plt.plot(x+1, iusi['CMO'], marker='d')
plt.title('Evolução do Custo Marginal de Operação ($)')
plt.xlabel('Período ou Mês de Planejamento')
plt.ylabel('Custo Marginal de Operação ($)')
plt.xticks(x+1)
plt.grid()
plt.tight_layout()

The error marks the third line. If necessary, I share the rest of the code. However it is extended, it has other functions besides the plotting.

  • It seems that you are trying to assemble a Dashboard, I advise you to share the dataset and the code you are using. You posted the error but did not post on which line it might be occurring, so it is complicated to help.

  • Really, there is little information rs. I’m new here too. I’ve managed to solve it. But thank you so much for the willingness to help!

1 answer

0


This error is generated when trying to access a position in a string using another string (see link). Since strings are not dictionaries, only integers can be used as index, returning the respective letter of that position.

I don’t have many details, so I guess the variable iusi can be (or contain a value that is) a string, and when you run iusi['CMO'], generates the error because one tries to access a position indexed by 'CMO' in this string.

  • Thank you! I was able to understand the error. The other variables were written in a different way. ẓ CMO' is a list inside a dictionary, and I was pointing to the key of the dictionary instead of pointing to the list when I used the for and enumerate. Just take the for and put (result["Dger"]["CMO"]) directly in the position of the data of the y axis that worked.

Browser other questions tagged

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