pythondictionary

Python Dictionaries


hoping you all can help. I am having a bit of trouble wrapping my head around importing a text file into a python dictionary. As an overview of my program, I am trying to take a text file (basicaly a CSV, but with a txt extention) Sample data from text file:

Cessna,234.1
Velocity,412.5
Beechcraft,467.2
Gulfstream,599.3 
Honda,412.1
Velocity,398.8
Velocity,343.9
Gulfstream,630.2
Honda,456.3
Cessna,221.3
Velocity,405.2
Honda,436.4

The final product I am hoping for is to combine like aircraft, for example Honda would be Honda: (3,1304.8) in the dictionary. Honda being the key, 3 is the number of like aircraft in the text file, 1304.8 bing total mile between all Honda aircraft.

This is the code i am using to read the text file into a list (print is just me looking at what my code is doing)

aircraft = []
aircraftDict = {}

infile = open(file, "r")
for item in infile:
    item = item.rstrip()
    aircraft.append(item)
    
print (aircraft)

infile.close()

I have no issues with reading a file into a list, this is my result as a list:

['Cessna,234.1', 'Velocity,412.5', 'Beechcraft,467.2', 'Gulfstream,599.3', 'Honda,412.1', 'Velocity,398.8', 'Velocity,343.9', 'Gulfstream,630.2', 'Honda,456.3', 'Cessna,221.3', 'Camry,4.2', 'Honda,436.4']

All is good here, data looks good.

I have two questions:

One: how do I combine the list items and get Honda, 1304.8 Two: more importantly, how do I create a dictionary out of the combined data with a tuple. For example:

{"Honda":(3,1304.8), next aircraft here} 

Again, the final dictionary would be: Aircraft Type:(Number of Aircraft, Mile total from all like aircraft)


Solution

  • Here's how I would do it

    with open("aircraft_data.txt", "r") as infile:
        for line in infile:
            # Split the line into aircraft type and mileage
            aircraft, mileage = line.strip().split(",")
            mileage = float(mileage)  # Convert mileage to a float
    
            # If the aircraft is already in the dictionary, update its count and mileage
            if aircraft in aircraft_dict:
                count, total_mileage = aircraft_dict[aircraft]
                aircraft_dict[aircraft] = (count + 1, total_mileage + mileage)
            else:
                # If the aircraft is not in the dictionary, add it with initial values
                aircraft_dict[aircraft] = (1, mileage)