Home > front end >  Python - 'int' object is not subscriptable" for in dict
Python - 'int' object is not subscriptable" for in dict

Time:01-01

My code does a for in on a list with several dicts inside, the code is working on the first item, but when it goes to the second, the error "'int' object is not subscriptable" occurs Since the item "cavalo" is not an int, but a string, I couldn't find anything that would help me.

from PyPDF2 import PdfReader, PdfWriter
import re

veiculos = [{"cavalo":"AAA1234","carretas":["CCC1234","DDD1234","EEE1234"]},{"cavalo":"BBB1234","carretas":["FFF1234","GGG1234","HHH1234"]}]

for i in veiculos:
    for conj in i.items():
        
        placa1 = i["cavalo"]
        placa2 = i["carretas"][0]
        placa3 = i["carretas"][1]
        placa4 = i["carretas"][2]

        pdf_file_path = 'IBAMA SP 30-03-2023.pdf'
        file_base_name = pdf_file_path.replace('.pdf', '')
        arquivo = PdfReader(pdf_file_path)
        NumPages = len(arquivo.pages)
        paginas = []
        paginas.append(0)

        for i in range(0, NumPages):
            PageObj = arquivo.pages[i]
            Text = PageObj.extract_text()
            if re.search(placa1,Text):
                paginas.append(i)

        for i in range(0, NumPages):
            PageObj = arquivo.pages[i]
            Text = PageObj.extract_text()
            if re.search(placa2,Text):
                paginas.append(i)

        for i in range(0, NumPages):
            PageObj = arquivo.pages[i]
            Text = PageObj.extract_text()
            if re.search(placa3,Text):
                paginas.append(i)

        for i in range(0, NumPages):
            PageObj = arquivo.pages[i]
            Text = PageObj.extract_text()
            if re.search(placa4,Text):
                paginas.append(i)

        paginas.append(len(arquivo.pages)-1)
        pdfWriter = PdfWriter()

        for page_num in paginas:
            pdfWriter.add_page(arquivo.pages[page_num])

        with open('{0}_subset.pdf'.format(placa1), 'wb') as f:
            pdfWriter.write(f)
            f.close()

I need "placa1" to receive "AAA1234" and then "BBB1234"...

CodePudding user response:

I wonder if you'd have luck changing

for i in veiculos:
    for conj in i.items():
        # rest of your function

to

for i,conj in veiculos.items():
    # rest of your function

CodePudding user response:

veiculos = [{"cavalo":"AAA1234","carretas":["CCC1234","DDD1234","EEE1234"]},{"cavalo":"BBB1234","carretas":["FFF1234","GGG1234","HHH1234"]}]
for i in veiculos:
for conj in i.items():
    print(conj)
    #placa1 = i["cavalo"]
    placa1 = conj[1]
    placa2 = i["carretas"][0]
    placa3 = i["carretas"][1]
    placa4 = i["carretas"][2]
  • Related