Python Forum
Store a set in a dictionary's value
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Store a set in a dictionary's value
#5
Quote:I have to read a file that contains a chronological list of the world series winning teams from 1903 to 2009
Who won in 1994?

First make sure you want a set instead of a list. A set is an unordered collection, and I think I would prefer my years to appear in order (probably is sorted in the data). Then I would use something like bowlofred does, except use .append() instead of .add().

I grabbed a list from the Encyclopedia Britannica website that looks like this
Output:
1903 Boston Americans (AL) Pittsburgh Pirates (NL) 5–3 1904 no series 1905 New York Giants (NL) Philadelphia Athletics (AL) 4–1 1906 Chicago White Sox (AL) Chicago Cubs (NL) 4–2
To stuff this into a dictionary I used this code:
with open('debug.txt', 'r') as file:
    ws_winner = {}
    while line := file.readline():
        try:
            year, winner, loser, score = line.strip().split('\t')
            winner = winner[:-5]
            year = int(year)
            if years := ws_winner.get(winner):
                years.append(year)
            else:
                ws_winner[winner] = [year]
        except:
            pass

for team, years in ws_winner.items():
    print(team, years)
Reply


Messages In This Thread
RE: Store a set in a dictionary's value - by deanhystad - Oct-04-2020, 03:20 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Read csv file, parse data, and store in a dictionary markellefultz20 4 4,743 Nov-26-2019, 03:33 PM
Last Post: DeaD_EyE

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020