简体   繁体   中英

Making a CSV list in Python

I am new to python and need help. I am trying to make a list of comma separated values. I have this data.

EasternMountain 84,844 39,754 24,509 286 16,571 3,409 315 
EasternHill 346,373 166,917 86,493 1,573 66,123 23,924 1,343 
EasternTerai 799,526 576,181 206,807 2,715 6,636 1,973 5,214 
CentralMountain 122,034 103,137 13,047 8 2,819 2,462 561 

Now how do I get something like this;

"EasternMountain": 84844,
"EasternHill":346373,

and so on??

So far I have been able to do this:

 fileHandle = open("testData", "r")
 data = fileHandle.readlines()
 fileHandle.close()

 dataDict = {}

 for i in data:
    temp = i.split(" ")

    dataDict[temp[0]]=temp[1]
    with_comma='"'+temp[0]+'"'+':'+temp[1]+','
    print with_comma

Use the csv module

import csv
with open('k.csv', 'r') as csvfile:
    reader = csv.reader(csvfile, delimiter=' ')
    my_dict = {}
    for row in reader:
        my_dict[row[0]] = [''.join(e.split(',')) for e in row[1:]]

print my_dict

k.csv is a text file containing:

EasternMountain 84,844 39,754 24,509 286 16,571 3,409 315 
EasternHill 346,373 166,917 86,493 1,573 66,123 23,924 1,343 
EasternTerai 799,526 576,181 206,807 2,715 6,636 1,973 5,214 
CentralMountain 122,034 103,137 13,047 8 2,819 2,462 561 

Output:

{'EasternHill': ['346373', '166917', '86493', '1573', '66123', '23924', '1343', ''], 'EasternTerai': ['799526', '576181', '206807', '2715', '6636', '1973', '5214', ''], 'CentralMountain': ['122034', '103137', '13047', '8', '2819', '2462', '561', ''], 'EasternMountain': ['84844', '39754', '24509', '286', '16571', '3409', '315', '']}

Try this:

def parser(file_path):
    d = {}
    with open(file_path) as f:
        for line in f:
            if not line:
                continue
            parts = line.split()
            d[parts[0]] = [part.replace(',', '') for part in parts[1:]]
    return d

Running it:

result = parser("testData")
for key, value in result.items():
    print key, ':', value

Result:

EasternHill : ['346373', '166917', '86493', '1573', '66123', '23924', '1343']
EasternTerai : ['799526', '576181', '206807', '2715', '6636', '1973', '5214']
CentralMountain : ['122034', '103137', '13047', '8', '2819', '2462', '561']
EasternMountain : ['84844', '39754', '24509', '286', '16571', '3409', '315']

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