[Python] Creating list of Dictionaries from .csv, mixed datatypes issue

Discussão em 'Python' iniciado por Stack, Julho 17, 2025.

  1. Stack

    Stack Membro Participativo

    I have imported a .csv and turned it into a list of dictionaries with the headings as the keys. However my values are a mix of string, int, float, and True/False. Is there an easy way to have these datatypes be converted, as they are all currently strings. Thanks! '''

    import csv
    with open("lens_specifications.csv",'r') as lenses_input:
    lenses = csv.DictReader(lenses_input)
    header_check = True
    lenses_dict = []
    for line in csv.reader(lenses_input):
    # line_stripped = []
    if header_check == True:
    line_stripped = [i.replace('"','') for i in line]
    keys = line_stripped
    header_check = False
    else:
    line_stripped = [i.replace('"','') for i in line]
    lens_dict = dict(zip(keys, line_stripped))
    lenses_dict.append(lens_dict)
    print(lenses_dict)


    '''

    Print Output: '''

    [{'Name': 'SEL2470GMII', 'Manufacturer': 'Sony', 'Zoom': 'True', 'Focal Length': '24', 'Max Aperture': '2.8', 'Min Aperture': '22', 'Min Focus Distance': '210', 'Focal Length Max': '70', 'Min Focus Distance^': '300', 'Fixed Aperture': 'True', 'Max Aperture^': '', 'Min Aperture^': ''}, {'Name': 'SEL50F14GM', 'Manufacturer': 'Sony', 'Zoom': 'False', 'Focal Length': '50', 'Max Aperture': '1.4', 'Min Aperture': '16', 'Min Focus Distance': '410', 'Focal Length Max': '', 'Min Focus Distance^': '', 'Fixed Aperture': '', 'Max Aperture^': '', 'Min Aperture^': ''}, {'Name': '150-600mm F5-6.3 DG DN OS', 'Manufacturer': 'Sigma', 'Zoom': 'True', 'Focal Length': '150', 'Max Aperture': '5', 'Min Aperture': '22', 'Min Focus Distance': '580', 'Focal Length Max': '600', 'Min Focus Distance^': '2800', 'Fixed Aperture': 'False', 'Max Aperture^': '6.3', 'Min Aperture^': '29'}]


    '''

    input .csv: '''

    """Name""","""Manufacturer""","""Zoom""","""Focal Length""","""Max Aperture""","""Min Aperture""","""Min Focus Distance""","""Focal Length Max""","""Min Focus Distance^""","""Fixed Aperture""","""Max Aperture^""","""Min Aperture^"""
    """SEL2470GMII""","""Sony""","""True""",24,2.8,22,210,70,300,"""True""",,
    """SEL50F14GM","""Sony""","""False""",50,1.4,16,410,,,,,
    """150-600mm F5-6.3 DG DN OS""","""Sigma""","""True""",150,5,22,580,600,2800,"""False""",6.3,29


    '''

    Continue reading...

Compartilhe esta Página