Home > Back-end >  python iterate loop and change values in dictionary
python iterate loop and change values in dictionary

Time:11-02

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' ...

CodePudding user response:

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]
for k,j in zip(years_list,lines):
   years.update({k:j})  # or more simply years[k] = j  
  • Related