Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate a Python dictionary with simultaneous converting certain strings to floats?

Let's say I have list of lists in matrix variable:

matrix = [['first', '1,1', 'last'], ['strng_1', '12231,71', 'st_2']]

As you can see, all nested lists are having float data written as string. I would like to convert them to float datatype. I need to create a dictionary and make this conversion simultaneously. For that reason, I've tried to make it using dictionary comprehension. So, these operations as one-liner might look like this:

dict_comp = {r[0]: r.insert(1, float(r[1].replace(',', '.'))).pop(2) for r in matrix if r}

But it doesn't work as expected. And now, after my previous question I know why exactly. Finally, I would like to ask about how to generate a dictionary with simultaneous converting certain strings to floats?

UPDATE

Expecting output:

{'first': ['first', 1.1, 'last'], 'strng_1': ['strng_1', 12231.71, 'st_2']}
like image 792
Quanti Monati Avatar asked Mar 06 '26 16:03

Quanti Monati


2 Answers

The following will work:

dict_comp = {r[0]: [r[0], float(str(r[1]).replace(',','.')), r[2]] for r in matrix if r}

# {'first': ['first', 1.1, '1,1'], 'strng_1': ['strng_1', 12231.71, 'st_2']}
like image 177
Carsten Avatar answered Mar 09 '26 06:03

Carsten


Change your locale to something that would understand comma as a decimal point, for example fr_FR.utf8, use locale.atof to convert the string to float, and then revert back your locale

import locale 
loc = locale.getlocale() 
locale.setlocale(LC_NUMERIC, 'fr_FR.utf8')

d = {a:[a, locale.atof(b), c] for a,b,c in matrix}

locale.setlocale(LC_NUMERIC, loc)

print (d)

Output

{'first': ['first', 1.1, 'last'], 'strng_1': ['strng_1', 12231.71, 'st_2']}
like image 35
Sunitha Avatar answered Mar 09 '26 06:03

Sunitha



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!