0

How do I use the index of a for loop in Python?

I'm trying to use .items(), but I did not succeed.

I know this is very basic. But I'm not getting it. I'm migrating from php to python and am encountering a few different things. Thank you

for index, linha in reg2.items():
        print(index, linha)

Error:

    for index, linha in reg2.items()
AttributeError: 'list' object has no attribute 'items'
5
  • items is used for dicts, you have a list. Given your current code, you're probably looking for enumerate Commented Sep 6, 2017 at 21:05
  • I intend to take the index to form an array with the result. I will edit the post for better understanding Commented Sep 6, 2017 at 21:14
  • You havent told us what data structure reg2 is
    – AlanK
    Commented Sep 6, 2017 at 21:20
  • with enumerate works, but another error occurred --- data['lista'][index]['name'] = linha.name, TypeError: list indices must be integers or slices, not str Commented Sep 6, 2017 at 21:27
  • I removed the edited-in code because it seems to me it is dealing with another error entirely. It's not good to edit new questions into old posts because it can invalidate the existing answers. If you can't fix the new problem by yourself, feel free to write a new question that addresses it.
    – trent
    Commented Sep 6, 2017 at 21:32

1 Answer 1

2

Get your index using enumerate()

for index, item in enumerate(reg2):
    print(index, item)
2
  • with enumerate works, but another error occurred --- data['lista'][index]['name'] = linha.name, TypeError: list indices must be integers or slices, not str Commented Sep 6, 2017 at 21:27
  • this is because you have data['lista'][(int)]['name'].. you cannot use 'lista' or 'name' because data is a list
    – AlanK
    Commented Sep 6, 2017 at 21:29

Not the answer you're looking for? Browse other questions tagged or ask your own question.