python iterate loop and change values in dictionary

Question:

enter image description here

I’m trying to iterate over the loop to change the value of the dictionary. lines have a different baseball teams in each line . When I print the years, it prints out the keys correctly, but the value is all changed to the last element of the lines.
For example,
1903: ‘NY Yankees’, 1905: ‘NY Yankees’ … 2021: ‘NY Yankees’.
How do I make it to assign the correct values into the dictionary?

    lines = a.readlines()
    print(lines)
    for i in range(1903,2022):
        if i == 1904:
            continue
        elif i == 1994:
            continue
        else:
            years.update({i:i})
            for j in lines:
                years.update({i:j})  

I expect to get when I print years,
1903:’First line in the lines’, 1905: ‘Second line in the lines’ …
What really resulted:
1903: ‘Last element in lines’ 1905: ‘Last element in lines’ …

Asked By: ChangJun Kim

||

Answers:

Dictionary keys are unique: for j in lines: years.update({i:j}) will update years[i] several times, keeping only the latest value, which will be the last line!

To fix that, iterate simultaneously on years’ keys and on the lines like this:
Note the you must unindent this to pull it out of your else: bloc .

Here’s the complete code, with the creation of the keys simplified:

lines = a.readlines()
print(lines)
years = {}
years_list = [i for i in range(1903,2022) if i != 1904 and i != 1994]
years = dict(zip(years_list,lines)) 
Answered By: Swifty
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.