简体   繁体   中英

Issue in creating dictionary using csv in python

I have a CSV in below format

我的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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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