所以我正在进行一项任务,我正在试图找出一个步骤,我们将采用csv文件并将其转换为字典。我的一个限制是不导入csv。在这里搜索关于将CSV文件转换为字典的其他问题时,所有问题都使用import csv。例如,如果我的CSV文件包含以下内容(第一行是标题):
"Headline","Newspaper", "Year Published", "Author"
"Crash", "New York Times", "2001", "Smith"
"Fire", "Washington Post", "2010", "Dudley"
"Addiction", "National Enquirer", "2008", "Kuhn"
如何在不导入csv的情况下将这些数据转换为Python中的字典?
我目前在做什么,我有一些伪代码,因为我知道我想要对这些部分执行什么,但我不是100%肯定如何这样做,因为这是我第一周使用文件和词典一起:
def read_file(filename):
d={}
with open(filename , 'r') as f:
first_line = f.readline()
for line in f:
if line.strip().isdigit():
# assign first string in line as key
#assign rest of strings in line as value to key in that line as a tuple
答案 0 :(得分:0)
从标题中提取密钥后,您可以转置剩余的行:
with open("foo.csv") as f:
# pull header line and split into keys
keys = next(f).strip().split(",")
# transpose remaining lines
values = zip(*(line.strip().split(",") for line in f))
# zip keys and values and create a dict
dct = dict(zip(keys, vals)
转置会逐列显示元素,因此它们将与每个标题键匹配。
答案 1 :(得分:0)
您可以为每一行创建一个包含字典项的列表,这更像是JSON样式格式。
with open(filename) as f:
keys = [val.strip().replace('"', '') for val in f.readline().split(',')]
result = []
for line in f:
line = [val.strip().replace('"', '') for val in line.split(',')]
result.append({key: val for key, val in zip(keys, line)})
>>> result
[{'Author': 'Smith',
'Headline': 'Crash',
'Newspaper': 'New York Times',
'Year Published': '2001'},
{'Author': 'Dudley',
'Headline': 'Fire',
'Newspaper': 'Washington Post',
'Year Published': '2010'},
{'Author': 'Kuhn',
'Headline': 'Addiction',
'Newspaper': 'National Enquirer',
'Year Published': '2008'}]