Search code examples
pythonordereddictionary

How to replace values in an ordered dictionary


I am reading in an example file as an ordered dictionary and want to replace some text ('xx' with '' or or null).I am struggling to understand how to do this.I have tried different methods and ended up with the code below and I cant understand why its not working. There must be a quicker way to do this - could anybody help please?

import csv
import os
my_path = os.path.abspath(__file__)
print('present working directory is \n' + my_path + '\n')
with open('test_xx.csv', 'r') as csv_file:
    csv_reader = csv.DictReader(csv_file)
    for line in csv_reader:
        for key, value in line.items():
            for item in value:
                if value is 'xx':
                    key[value] = ''
        print(line.values())
## test data file
Title1, Title2, Title3, Title4, Title5
1,2,3,4,5
6,7,xx,9,10
11,12,xx,14,15
16,17,18,19,10

Solution

  • This should do it:

    with open('test.csv', 'r') as csv_file:
        csv_reader = csv.DictReader(csv_file)
        for line in csv_reader:
            for key, value in line.items():
                if (value == "xx"):
                    line.update({key: " "})
            print(line.values())
    

    Output:

    odict_values(['1', '2', '3', '4', '5'])
    odict_values(['6', '7', ' ', '9', '10'])
    odict_values(['11', '12', ' ', '14', '15'])
    odict_values(['16', '17', '18', '19', '10'])
    

    line is the ordered dictionary (for each line in the file). It is updated when one of its values is equal to xx.