简体   繁体   中英

Changing output values in a dictionary from strings to floats and/or integers in Python

So far I have this code:

def read_file(filename):

    with open("menu1.csv") as file:
        file.readline()
        for line in file:
            line_strip = [line.rstrip('\n')]
            lines= [line.split(',')]
            result = {key: tuple(val) for key, *val in lines}
            print(result)

and i get the following output:


{'Chic-fil-A Chicken Sandwich': ('3.75', '440', 'Entrees\n')}

{'Chic-fil-A Deluxe Sandwich': ('4.45', '500', 'Entrees\n')}

{'Spicy Chicken Sandwich': ('3.99', '460', 'Entrees\n')}

{'Spicy Deluxe Sandwich': ('4.69', '550', 'Entrees\n')}

{'Grilled Chicken Sandwich': ('5.15', '320', 'Entrees\n')}

{'Grilled Chicken Club': ('6.55', '460', 'Entrees\n')}

The output continues but that is just a part of it. I need to make the first number in the () a float, and the second one an integer. For example, for the first output listed, I need the '3.75' to be a float 3.75 and the '440' to be an integer 440.

ALSO how do i make the '\n' not show up in the output?? I need the output to stay stacked on top of each other like it is. But without the '\n' showing up with it.

Thank you!

It seems like you can directly do this while constructing the dictionary:

def read_file(filename):

    with open("menu1.csv") as file:
        file.readline()
        for line in file:
            line_strip = [line.rstrip('\n')]
            lines= [line.split(',')]
            result = {key: (float(fl), int(intg), text.strip()) 
                            for key, fl, intg, text in lines}
            print(result)

This may work (considering I did not make any mistake) as a shorter version (not sure how short it actually is:P):

def read_file(filename):

    with open("menu1.csv") as file:
        result = {key: (float(fl), int(intg), text.strip())
                        for line in file 
                        for key, fl, intg, text in [line.strip().split(',')]}
        print(result)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM