1

This is my dictionary {'0':'Denver', '1':'Chicago', '2':'Maryland'}

in the csv files I have 0 1 1 0 2 2 3 2 I would like to change the numbers in the CSV file to the values in the dictionary: 0 Chicago 1 Denver 2 Maryland 3 Maryland

1 Answer 1

1
d = {'0':'Denver', '1':'Chicago', '2':'Maryland'}

# we'll start by creating a new file to write the output to
with open("output_filename.csv", "w+") as out_file:
    # So the first piece is reading the file in python
    with open("filename.csv") as in_file:
        # next you'll want to loop over each line
        for line in in_file:
            # Now we can split the string into elements by the whitespce
            line_list = line.split(" ")
            # line_list = ['0', '1', '1', '0', '2', '2', '3', '2']
            # we can loop over the list taking alternating elements and looking them up
            result = " ".join([d[item] if index % 2 else item for index, item in enumerate(line_list)])
            out_file.write(result)

The real "work" is happening in this line: result = " ".join([d[item] if index % 2 else item for index, item in enumerate(line_list)])

enumerate returns the index and the value as we loop over the line_list so (0, '0'), (1, '1'), (2, '1') ...

then the turnery is using the modulo % to see what the remainder is when dividing by 2 (ie if the index is 0, 2, 4, ...) and using the dictionary to look up the value if it isn't (ie index 1, 3, 5...)

Sign up to request clarification or add additional context in comments.

4 Comments

I suppose the "line_list" is my dictionary. how about the "d"? I'm getting not defined
Sorry, I added d -- that's the dictionary the "line_list" is created by splitting the string from your csv "0 1 1 0 2 2 3 2" by it's whitespace line_list = line.split(" ") resulting in ['0', '1', '1', '0', '2', '2', '3', '2']
Maybe I need to clarify a bit. my dictionary has keys and values. Now, these keys are the only values in a CSV file and I want to loop through the CSV file and replace the values with the Key Values from my dictionary where the value = key. IF (ValueInCSV = KeyInDictionary) ValueInCSV = KeyInDictionary->Value
My code above takes "0 1 1 0 2 2 3 2" and ouputs "0 Chicago 1 Denver 2 Maryland 3 Maryland" You just need to replace "filename.csv" with your actual filename, and "output_filename.csv" with the desired output file

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.