我有以下格式的CSV
我想将其转换为以下格式的字典
{'Feature': 'Delivery', 'Subfolders': 'Child - 1', 'Child - 2' 'Child - 3' 'Child - 4' 'Child - 5', 'Child - 6'.... till 'Child -13'}
到目前为止,我已经完成了以下代码,但是却得到了这样的输出,
{'Feature': 'Delivery', 'Subfolders': 'Child - 1'}
import csv
with open('features.csv', mode='r') as infile:
reader = csv.reader(infile)
mydict = {rows[0]: rows[1] for rows in reader}
print(mydict)
有想法吗?
答案 0 :(得分:2)
这个怎么样?我刚刚添加了一个过滤器和列表切片。
with open('test.csv', mode='r') as f:
reader = csv.reader(f)
checker = lambda i: bool(i and i.strip()) # Conditions to check whether a string is empty or not
mydict = {rows[0]: list(filter(checker, rows[1:])) for rows in reader}
print(mydict)
结果:
{'Feature': ['Delivery'], 'Subfolder': ['Child - 1', 'Child - 2', 'Child - 3', 'Child - 4', 'Child - 5', 'Child - 6', 'Child - 7', 'Child - 8', 'Child - 9', 'Child - 10', 'Child - 11', 'Child - 12', 'Child - 13']}
其他答案:
根据您的评论,如果我理解正确,则希望从给定键中获取值。
如果您要处理几个键,只需将每个键分配给一个新变量
features = mydict['Feature']
subfolders = mydict['Subfolder']
print(features, subfolders)
# ['Delivery'] ['Child - 1', 'Child - 2', 'Child - 3', 'Child - 4', 'Child - 5', 'Child - 6', 'Child - 7', 'Child - 8', 'Child - 9', 'Child - 10', 'Child - 11', 'Child - 12', 'Child - 13']
答案 1 :(得分:1)
这是另一种方式。
import csv
with open('test.csv', mode='r') as infile:
reader = csv.reader(infile)
mydict = dict()
for rows in reader:
cnt = 0
for row in rows:
if cnt == 0:
mydict[row] = list()
cnt += 1
else:
mydict[rows[0]].append(row)
print(mydict)
结果:
{'this': ['1', '2'], 'That': ['2', 'as']}
答案 2 :(得分:0)
import csv
with open('features.csv', mode='r') as infile:
reader = csv.reader(infile)
mydict = {}
for i in reader:
if '' in i:
mydict[i[0]] = i[1:2]
else:
mydict[i[0]] = i[1:]
print(mydict)
结果
{'Feature': ['Delivery'], 'subfolders': ['Child – 1', 'Child – 2', 'Child – 3', 'Child – 4', 'Child – 5', 'Child – 6', 'Child – 7', 'Child – 8']}
然后
features = mydict['Feature']
subfolders = mydict['subfolders']
print(features)
print(subfolders)