user15135772
user15135772

Reputation:

Save csv file to an array in dictionary

I have a csv file with this data:

Sensor 1;;
x;o;o
o;x;x
x;x;o
Sensor 2;;
o;x;o
x;x;o
o;o;o
Sensor 3;;
x;o;x
x;x;o
x;x;x

What the program should do is ask you which sensor you want and return the sensor name and show the path as an array within a dictionary. An example would be the following:

Sensor 1 : press 1
Sensor 2 : press 2
Sensor 3 : press 3

{Sensor 1: [[x,o,o],[o,x,x],[x,x,o]]}

This is the code I've tried:

f=open('file.csv','r')
dic={}
key=""
s=f.readlines()
for line in s:
    row=line.split(';')
    if "Sensor" not in line:
        if key:
            dic[key].append(row)
    else:
        key=row[0]
        dic[key]=[]
print(dic)

The code cannot have imports

Upvotes: 1

Views: 60

Answers (2)

Krishna Chaurasia
Krishna Chaurasia

Reputation: 9572

The problem is that you have defined dic as list [] but it should be a dictionary dict().

Other than that, you might also want to use rstrip() to trim \n characters and split the line to get a list. Currently, you are appending each line which is a str object to each sensor's list.

f=open('file.csv','r')
dic=dict()                # this is a dictionary
s=f.readlines()
key = ""
for line in s:
    if "Sensor" not in line:
        if key:
            line = line.rstrip()
            line = line.split(';')
            dic[key].append(line)
    else:
        row = line.split(';')
        key=row[0]
        dic[key]=[]
print(dic['Sensor 1'])

Edit based on the comment.

If you need one more level of indexing, you can modify the generated list to add a new key with the number of the sensor.

f=open('file.csv','r')
dic=dict()
s=f.readlines()
key = ""
for line in s:
    if "Sensor" not in line:
        if key:
            line = line.rstrip()
            line = line.split(';')
            dic[key].append(line)
    else:
        
        row = line.split(';')
        key=row[0]
        dic[key]=[]

sensor_dict = dict()
for k, v in dic.items(): 
    sensor_dict[k.split()[-1]] = {k: v}

user_input = input('Which sensor you want (1,2,3): ')
print(sensor_dict[user_input])

Output:

Which sensor you want (1,2,3): 3
{'Sensor 3': [['x', 'o', 'x'], ['x', 'x', 'o'], ['x', 'x', 'x']]}

Upvotes: 0

Epsi95
Epsi95

Reputation: 9047

You can try to parse the string to get desired output

data = open('temp.csv').readlines()

current_sensor = None
sensor_dict = {}
for each_line in data:
    if each_line.startswith('Sensor'):
        sensor_name = each_line.replace(';', '').replace('\n', '')
        current_sensor = sensor_name
        sensor_dict[current_sensor] = []
    else:
        sensor_dict[current_sensor].append(each_line.replace('\n', '').split(';'))

# print(sensor_dict)

print("""Sensor 1 : press 1
Sensor 2 : press 2
Sensor 3 : press 3
""")

user_input = 'Sensor ' + input('Which sensor you want (1,2,3): ')
print(sensor_dict[user_input])
Sensor 1 : press 1
Sensor 2 : press 2
Sensor 3 : press 3

Which sensor you want (1,2,3): 1
[['x', 'o', 'o'], ['o', 'x', 'x'], ['x', 'x', 'o']]

Upvotes: 1

Related Questions