Remove only leading zeros from sorted dictionary keys

Question:

This is my code

file_name = input()

shows = {}


with open(file_name, 'r') as file:
    lines = file.readlines()
    for i in range(0, len(lines), 2):
        season = lines[i].strip('n')
        name = lines[i+1].strip('n')
        if(season in shows):
            shows[season].append(name)
        else:
            shows[season] = [name]
    
    
    with open('output_keys.txt', 'w+') as f:
        for key in sorted (shows.keys()):
            f.write('{}: {}n'.format(key, '; '.join(shows.get(key))))
            print('{}: {}'.format(key, '; '.join(shows.get(key))))
      
    titles = []      
    for title in shows.values():
        titles.extend(title)
        
    with open('output_titles.txt', 'w+') as f:
        for title in sorted(titles):
            f.write('{}n'.format(title))
            print(title)
        
            

The problem is with my output_keys files, leading zeros is the only differing output:

Leading zeros is the only differing output

I’ve tried using .strip('0') after the key But then that also removes the trailing zero and messes up the numbers that end in zero.

Asked By: Tyler

||

Answers:

I think you need to change this line:

f.write('{}: {}n'.format(key, '; '.join(shows.get(key))))

to this:

f.write('{}: {}n'.format(key.lstrip("0"), '; '.join(shows.get(key))))

lstrip("0") will remove a "0" only if it as the start/left of a string.

Here are some examples to make that clearer:

>>>"07: Gone with the Wind, Rocky".lstrip('0')
'7: Gone with the Wind, Rocky'
>>>"17: Gone with the Wind, Rocky".lstrip('0')
'17: Gone with the Wind, Rocky'
Answered By: osint_alex

i know this is really old, but the lstrip worked for me like a charm. My code is way different that the example above, but I was able to determine where in my code i needed to put the lstrip and it worked on my first run.
Thank you for saving my brain from reaching a melt down trying to figure out what I needed to do!

Answered By: DavidS
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.