简体   繁体   中英

Convert CSV file into 2D Table in Python

I have a CSV file with the following structure:

Configuration ID, Value (1), Value (2), ......., Value (N)
Config (1)      , X (1)    , X (2)    , ......., X (N)
Config (2)      , Y (1)    , Y (2)    , ......., Y (N)

The configuration ID for each row is unique across the file.

I want to read this CSV file in Python (v3.8) and be able to lookup for a particular value by passing both the Config ID and Value ID (Something like 2D dictionary)

print(dataStucture[Config (1)][Value (2)])

The previous syntax should print: X(2)

Is there any embedded function in Python that parses a CSV file and converts it into 2D dictionary or any data structure that allows me to pass two unique keys to fetch a value from the CSV file? Any hint would be highly appreciated.

If you do not want to use pandas but csv instead, you can use the following code:

import csv

data_stucture = {}
with open('sample.csv') as csvfile:
    spamreader = csv.reader(csvfile)
    header = next(spamreader, None)  # skip the headers
    for row in spamreader:
        data_stucture[row[0].strip()] = {
            key.strip(): value.strip() for key, value in zip(header[1:], row[1:])
        }

Considering how the file is structured, the content of data_structure will be

{'Config (1)': {'Value (1)': 'X (1)', 'Value (2)Value (N)': 'X (2)'},
 'Config (2)': {'Value (1)': 'Y (1)', 'Value (2)Value (N)': 'Y (2)'}}

This means you will be able to get "X (1)" by using data_stucture['Config (1)']['Value (1)'] .

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