ChangeMyName
ChangeMyName

Reputation: 7408

How to convert values to float and assign them to a dictionary in Python?

I am trying to read content from a CSV file and store them in a dictionary.

Each row of my CSV file is formatted as:

'Node_001', '0.0067', '0.2456', '0.7896', ......

The first element will be used as key in dictionary, while the rest part are values.

Since these values are generated by equations in excel, I don't think there are anything wrong with the format itself.

Here is my code:

with open(path, "rb") as file:
    reader = csv.reader(file)

    my_dictionary = dict()           

    for row in reader:
        node_id = row[0]
        temp_values = row[1:]
        [float(x) for x in temp_values]
        my_dictionary[node_id] = temp_values 
        print isinstance(temp_values[0], float)

I print the first element of the numeric part of my rows to exam if they are converted to float. However, all I got is False.

So, may I know what is wrong with my code?

Thanks.

Upvotes: 0

Views: 207

Answers (4)

LSchueler
LSchueler

Reputation: 1514

You are not saving the conversion:

temp_values = [float(x) for x in temp_values]

If you replace your list comprehension with this one, your code should work.

Upvotes: 1

Burhan Khalid
Burhan Khalid

Reputation: 174614

Try this for a change, assuming you only have unique keys in your file:

with open(path, 'r') as f:
    reader = csv.reader(f)
    d = {r[0]:map(float, r[1:]) for r in reader}
print(d)

You can also stick with a list comprehension with this:

with open(path, 'r') as f:
    reader = csv.reader(f)
    d = {r[0]: [float(i) for i in r[1:]] for r in reader}

Upvotes: 1

mfcabrera
mfcabrera

Reputation: 781

The line [float(x) for x in temp_values] does not modify temp_values but creates a new list. you have to reassign it like:

with open(path, "rb") as file:
reader = csv.reader(file)

my_dictionary = dict()           

for row in reader:
    node_id = row[0]
    temp_values = row[1:]
    temp_values = [float(x) for x in temp_values]
    my_dictionary[node_id] = temp_values 
    print isinstance(temp_values[0], float)

Upvotes: 1

bgporter
bgporter

Reputation: 36454

This chunk of code:

for row in reader:
    node_id = row[0]
    temp_values = row[1:]
    [float(x) for x in temp_values]
    my_dictionary[node_id] = temp_values 
    print isinstance(temp_values[0], float)

creates a list of float values with this line:

    [float(x) for x in temp_values]

...but since it's not assigned to anything, it goes away immediately.

changing that line to

    temp_values = [float(x) for x in temp_values]

creates the converted list and assigns it to temp_values so the rest of your code can use those values.

Upvotes: 1

Related Questions