简体   繁体   English

在python中使用csv创建字典时出现问题

[英]Issue in creating dictionary using csv in python

I have a CSV in below format 我有以下格式的CSV文件

我的CSV

Where i want to convert it to dictionary in the below format, 我想将其转换为以下格式的字典,

    {'Feature': 'Delivery', 'Subfolders': 'Child - 1', 'Child - 2' 'Child - 3' 'Child - 4' 'Child - 5', 'Child - 6'.... till 'Child -13'}

So far I had done the following code but am getting output like this, 到目前为止,我已经完成了以下代码,但是却得到了这样的输出,

    {'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)

Thoughts? 思考?

How about this? 这个怎么样? I just added a filter and list slicing. 我刚刚添加了一个过滤器和列表切片。

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)

Results: 结果:

{'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']}

Additional answer: 附加答案:

According to your comment, if I understand correctly, you'd like to get values from a given key. 根据您的评论,如果我理解正确,则希望从给定键中获取值。

If you have one a few keys to deal with, you can simply assign each one of them in a new variable 如果您要处理几个键,则只需将每个键分配给一个新变量

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']

Just another way of doing it. 只是另一种方式。

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)

Result: 结果:

{'this': ['1', '2'], 'That': ['2', 'as']}
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)

Result 结果

{'Feature': ['Delivery'], 'subfolders': ['Child – 1', 'Child – 2', 'Child – 3', 'Child – 4', 'Child – 5', 'Child – 6', 'Child – 7', 'Child – 8']}

Then 然后

features = mydict['Feature']
subfolders = mydict['subfolders']

print(features)
print(subfolders)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM