'How can I loop through a csv file and replace values in it with a python dictionary
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
Solution 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...)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
