Handling elements in a file

Not that brevity is the be all and end all, but here’s what I got:

results = {}

print("Reading data file.")
with open("data", mode="r", encoding="UTF-8") as data:
    for line in data:
        sample = line.strip().split(',')
        key = ':'.join(sorted(sample[0].split(':')))
        value = float(sample[1])
        prev_val = results.setdefault(key, value)
        results[key] = max(prev_val, value)

print("Writing data to file..")
with open("output", mode='w', encoding="UTF-8") as output:
    for key, value in results.items():
        data = f"{key}, {value}\n"
        output.write(data)

print("Script exit")

dict.setdefault is really handy when you find yourself writing if key not in dict: put_the_item_in_the_dict

And I PEP-8’d the names :slight_smile:

2 Likes