user10255809
user10255809

Reputation:

How to convert the values of a list of dictionaries from a string to a float in Python

I want to change the Values of my Json data from a string to a float. My example Json is below.

input_dicts = [d["QN_9"]for d in input_dicts]
[{"STATIONS_ID": "44", "MESS_DATUM": "2018020800", "QN_9": "3", "TT_TU": "-6.6", "RF_TU": "96.0"}, {"STATIONS_ID": "44", "MESS_DATUM": "2018020801", "QN_9": "3", "TT_TU": "-6.8", "RF_TU": "98.0"}]

It should be Something like this "QN_9" : 3 instead of "QN_9" : "3"

So overall the final result looks like this

[{"STATIONS_ID": "44", "MESS_DATUM": "2018020800", "QN_9": 3, "TT_TU": -6.6, "RF_TU": 96.0}

Upvotes: 0

Views: 415

Answers (3)

user10255809
user10255809

Reputation:

        df = pd.DataFrame(input_dicts)
        df['STATIONS_ID'] = df['STATIONS_ID'].astype(str)
        df['MESS_DATUM'] = pd.to_datetime(df['MESS_DATUM'], format='%Y%m%d%H')
        df['QN_9'] = df['QN_9'].astype(int)
        df['TT_TU'] = df['TT_TU'].astype(float)
        df['RF_TU'] = df['RF_TU'].astype(float)

        return func.HttpResponse(df.to_json(orient='records'), mimetype='application/json')

I was able to easily do it via Pandas. I think this way is the neater version as the way Sayandip suggested was to convert every thing into a float including the things i needed as strings. Thank you for the help!~

Upvotes: 0

Sayandip Dutta
Sayandip Dutta

Reputation: 15872

You can get your desired result in this process:

input_dict = [{"STATIONS_ID": "44", "MESS_DATUM": "2018020800", "QN_9": "3", "TT_TU": "-6.6", "RF_TU": "96.0"}, {"STATIONS_ID": "44", "MESS_DATUM": "2018020801", "QN_9": "3", "TT_TU": "-6.8", "RF_TU": "98.0"}]
output_dict = [{key:float(elem[key]) for key in elem} for elem in input_dict]
>>> output_dict
[{'STATIONS_ID': 44.0,
  'MESS_DATUM': 2018020800.0,
  'QN_9': 3.0,
  'TT_TU': -6.6,
  'RF_TU': 96.0},
 {'STATIONS_ID': 44.0,
  'MESS_DATUM': 2018020801.0,
  'QN_9': 3.0,
  'TT_TU': -6.8,
  'RF_TU': 98.0}]

Upvotes: 1

Ashok KS
Ashok KS

Reputation: 691

Check if the below one works for you.

If the dictionary is something like below.

dic = {"QN_9": "3", "QN_10": "10"}

You can convert the keys to float or int using dictionary comprehension.

{k:int(v) for (k,v) in dic.items()}

The output would be like below.

{'QN_9': 3, 'QN_10': 10}

Upvotes: 1

Related Questions