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 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. 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)
Sign up to request clarification or add additional context in comments.

2 Comments

with enumerate works, but another error occurred --- data['lista'][index]['name'] = linha.name, TypeError: list indices must be integers or slices, not str
this is because you have data['lista'][(int)]['name'].. you cannot use 'lista' or 'name' because data is a list

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.