-5

I know it may seem like a simple question, but I really could not figure it out ... How to solve?

>>> itens = [{}]
>>> i = 0
>>> itens[i]['vendedor'] = 1
>>> i = 1
>>> itens[i]['vendedor'] = 2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
martineau
  • 119,623
  • 25
  • 170
  • 301
  • Why do you need the dict to be in a list? – Olivier Melançon May 14 '18 at 22:43
  • 1
    `[{}]` is a list with contains one empty dictionary. Because it has only one item (which is obviously in position 0), no error is raised when you try to access `itens[0]`. But when you try `itens[1]`, the error is raised, because there is no second element in your list. If your initial list was, for example, `[{}, {}]` then `itens[1]` would return your second `{}`, and no error would be raised. – rafaelc May 14 '18 at 22:48

2 Answers2

0

Since there is a single item in the list, getting the index 1, which is the second position in a list, raises and error.

What you probably want to do is append another dict to your list.

>>> items = [{}]
>>> items [0]['vendedor'] = 1
>>> items.append({})
>>> items [1]['vendedor'] = 2
>>> items
[{'vendedor': 1}, {'vendedor': 2}]
Olivier Melançon
  • 21,584
  • 4
  • 41
  • 73
0

Thanks for the reply, helped me!

I was able to solve my problem, I do not think I explained it correctly. I needed this:

import json

itens = []
indice = 0
nomes = ['A', 'B', 'C']

for n in nomes:
    indice = indice + 1
    dic = dict()
    dic[n] = indice
    itens.append(dic)

print(json.dumps(itens))

Thanks :-)

0sVoid
  • 2,547
  • 1
  • 10
  • 25