Search code examples
pythonpython-3.xdictionarytuplesiterable-unpacking

How to read from a file into a dict with string key and tuple value?


For an assignment, I'm creating a program that retrieves from a file information regarding Olympic countries and their medal count.

One of my functions goes through a list in this format:

Country,Games,Gold,Silver,Bronze
AFG,13,0,0,2
ALG,15,5,2,8
ARG,40,18,24,28
ARM,10,1,2,9
ANZ,2,3,4,5

The function needs to go through this list, and store into a dictionary with the country name as a key, and the remaining four entries as a tuple.

Here is what I am working with so far:

def medals(string):
    '''takes a file, and gathers up the country codes and their medal counts
    storing them into a dictionary'''

    #creates an empty dictionary
    medalDict = {}
    #creates an empty tuple
    medalCount = ()
    #These following two lines remove the column headings
    with open(string) as fin:
        next(fin)

        for eachline in fin:
            code, medal_count = eachline.strip().split(',',1)
            medalDict[code] = medal_count

    return medalDict

Now, the intent is for the entries to look something like this

{'AFG': (13, 0, 0, 2)}

Instead, I'm getting

{'AFG': '13,0,0,2'}

It looks like it is being stored as a string, and not a tuple. Is it something to do with the

medalDict[code] = medal_count

line of code? I'm not too sure how to convert that into separate integer values for a tuple neatly.


Solution

  • You are storing the whole string '13,0,0,2' as value, so

    medalDict[code] = medal_count
    

    should be replaced by:

    medalDict[code] = tuple(medal_count.split(','))
    

    Your original thought is correct, with this line being the sole exception. What is changed is now it splits the '13,0,0,2' into a list ['13', '0', '0', '2'] and converts it into a tuple.

    You can also do this to convert strings inside into integers:

    medalDict[code] = tuple([int(ele) for ele in medal_count.split(',')])
    

    But make sure your medal_count contains only integers.