如何替换有序字典中的值
How to replace values in an ordered dictionary
我正在阅读一个示例文件作为一个有序的字典,并想替换一些文本('xx' 为 '' or or null)。我正在努力理解如何做 this.I尝试了不同的方法并以下面的代码结束,我不明白为什么它不起作用。必须有一个更快的方法来做到这一点 - 有人可以帮忙吗?
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
应该这样做:
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())
输出:
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
是有序字典(对于文件中的每一行)。当其中一个值等于 xx
.
时更新
我正在阅读一个示例文件作为一个有序的字典,并想替换一些文本('xx' 为 '' or or null)。我正在努力理解如何做 this.I尝试了不同的方法并以下面的代码结束,我不明白为什么它不起作用。必须有一个更快的方法来做到这一点 - 有人可以帮忙吗?
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
应该这样做:
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())
输出:
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
是有序字典(对于文件中的每一行)。当其中一个值等于 xx
.