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
#1
Hello everyone. I am having trouble understanding how to store a set in a dictionary's value.

I have to read a file that contains a chronological list of the world series winning teams from 1903 to 2009, where the first line in the file is the name of the team that won in 1903 and the last line in the file is the name of the team that own in 2009.

I have a function called get_dict that will take the team_list (a list of the teams that won) and build a dictionary, so keys ware individual team names found in the file, and each values is a set that contains the year in the file where the team won.

So, I read the file and store the team names in a list, then create a dictionary with it. I created the function before I realized I had to use sets in the dictionary's value. But I don't know how to use the sets. Can you look at my function and tell me where I can go from here?
def get_dict(team_list):
    winning_dict = {}
    value = 1903    
    for index in team_list:
        winning_dict[index] = value
        value += 1

    return winning_dict
Reply
#2
Look up how to use a set? Actually storing a set in a dictionary is no different to storing anything else: just associate the value with a key.
Reply
#3
# a dict value that is a set
d['Cubs'] = set()
# adding members to the set
d['Cubs'].add(1907)
d['Cubs'].add(1908)
d['Cubs'].add(2016)
# display contents of the set
print(d['Cubs'])
This might be a nice place to use a defaultdict. If it defaults to a set, you don't have to create the set for each winner before adding to it.

from collections import defaultdict
d = defaultdict(set)
d['White Sox'].add(1906)
d['Cubs'].add(1907)
print(d['Cubs'])
Reply
#4
Something like this?

from collections import defaultdict


def get_dict(team_list):
    year = 1903
    winning_dict = defaultdict(set)
    for index in team_list:
        winning_dict[index].add(year)
    return winning_dict
Reply
#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
#6
(Oct-04-2020, 06:16 AM)bowlofred Wrote: This might be a nice place to use a defaultdict.
I have not learned about this yet. I have updated my code a bit to this:
def get_dict(team_list):
winning_dict = {}
value = 1903
team_set = set()
for index in team_list:
    if index in winning_dict:
        winning_dict[index] = team_set.add(value)
    if index not in winning_dict:
        winning_dict[index] = team_set(value)
    value += 1

return winning_dict
How ever, in line 7 I get the following error message:
Function 'add' doesn't return anything.
And then in line 9 I get this error message:
'set' object is not callable.

Why am I getting these errors?

I asked my teacher about how I should write this function and she gave me the following psudeucode:
use a count starting at 1903
read all lines from the file, since each line is a winner team of that year
if the team is already in your dict, just add the year to the set
if the team is not in your dict, just create a set with one year
increment count

I added the psudeucode so yall know what I am supposed to do.
Reply
#7
In line 4 you're creating a single set and trying to use it later. But every team need their own set. So you have to create it when it doesn't exist, and you don't need to keep track of it outside the dict.

In line 7, your dict value should already be a set. You want to modify that value (with add() method, not replace the value with something else.

Inn line 9, you need to create a (new) set, not reference a previously created one.
Reply
#8
Ok so I updated my code again and it seems to work so far
def get_dict(team_list):
    winning_dict = {}
    value = 1903
    for index in team_list:
        winning_dict[index] = set()
        if index in winning_dict:
            winning_dict[index].add(value)
        elif index not in winning_dict:
            winning_dict[index] = set(value)
        value += 1

    return winning_dict
Does this look ok to you?

Ok so I guess I do still have some problems with my code. When I try to display the winning years for a team, it is not correct. In fact, each team's winning years I try to display are exactly the same. However, there could be a problem with my code to display the team's winning years. In main I ask the user to enter a team's name and then I display the team's winning years:
#a call to the get_dict function
winning_dict = {}
winning_file = open('WorldSeriesWinners.txt', 'r')
team_list = winning_file.readlines()
winning_file.close()
for index in range(len(team_list)):
     team_list[index] = team_list[index].rstrip('\n')
     winning_dict = get_dict(team_list)

#now to display a team's winning years
key = input("Enter a team's name: ")
for key in winning_dict:
     result = winning_dict.get(key, 'Team not found')
     print(result, end=' ')
But it doesn't matter which team I enter because they all display the same thing:
Output:
{1903} {1994} {1954} {2005} {1908} {1979} {1930} {2007} {1914} {1990} {1948} {2000} {1924} {2006} {1984} {1955} {1957} {1988} {1983} {1986} {1989} {2008} {1985} {1991} {1993} {1995} {2003} {2001} {2002}
First of all, the curly brackes are not supposed to be displayed and these are NOT the correct winning years.

Also, the years are out of order for some reason?
Reply
#9
In line 5, you're erasing anything that might previously have been stored at that index. So if index is the Cubbies and we're at 1908, it will overwrite the previous set that held 1907.
Reply
#10
Perfect! thank you for all the help, deleting that line made my code work!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Read csv file, parse data, and store in a dictionary markellefultz20 4 4,601 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