简体   繁体   English

将字典列表中的值从字符串转换为浮点型

[英]Converting values in a list of dictionaries from string to float

I have a list of dictionaries, where each item in each dictionary is a string. 我有一个词典列表,其中每个词典中的每个项目都是一个字符串。 I am trying to build a formula to pass the whole dataset through and convert all values to a float. 我试图建立一个公式来传递整个数据集,并将所有值转换为浮点数。

Each dictionary has the following structure: 每个字典具有以下结构:

{'dropoff_datetime': '2014-11-26T22:31:00.000',
 'dropoff_latitude': '40.746769999999998',
 'dropoff_longitude': '-73.997450000000001',
 'fare_amount': '52',
 'imp_surcharge': '0',
 'mta_tax': '0.5',
 'passenger_count': '1',
 'payment_type': 'CSH',
 'pickup_datetime': '2014-11-26T21:59:00.000',
 'pickup_latitude': '40.64499',
 'pickup_longitude': '-73.781149999999997',
 'rate_code': '2',
 'tip_amount': '0',
 'tolls_amount': '5.3300000000000001',
 'total_amount': '57.829999999999998',
 'trip_distance': '18.379999999999999',
 'vendor_id': 'VTS'}

I am trying to cast the values into floats 我正在尝试将值转换为浮点数

def float_values(trips):    
    for trip in trips:
        for value in trip:
            trip[value] = float(trip[value])

I am getting error message string indices must be integers 我收到错误消息字符串索引必须为整数

You can iterate over the dictionary using items() or iteritems() depending on your version of python. 您可以根据您的python版本,使用items()iteritems()遍历字典。 Some of the values in your dictionary are strings, and therefore, can't be converted. 词典中的某些值是字符串,因此无法转换。 A naive solution is as follows: 一个简单的解决方案如下:

def float_values(trips):
    for key, value in trips.items():
        try:
            trips[key] = float(value)
        except ValueError:
            continue

You could also change this to use a comprehension if you so wish, but take care with the isdigit() function 如果愿意,您也可以将其更改为使用理解,但请注意isdigit()函数

def float_values(trips):
    return {key: float(value) if value.isdigit() else value for key, value in trips.items()}

Add the required code and insert some basic debugging. 添加所需的代码并插入一些基本调试。 See this lovely debug blog for help. 请参阅这个可爱的调试博客以获取帮助。

def float_values(trips):
    for trip in trips:
        print("trip =", trip)
        for value in trip:
            print("value =", value)
            trip[value] = float(trip[value])

data = {
    'dropoff_datetime': '2014-11-26T22:31:00.000',
    'dropoff_latitude': '40.746769999999998',
    'dropoff_longitude': '-73.997450000000001',
 }

float_values(data)

Output: 输出:

trip = dropoff_datetime
value = d
Traceback (most recent call last):
  File "so.py", line 14, in <module>
    float_values(data)
  File "so.py", line 6, in float_values
    trip[value] = float(trip[value])
TypeError: string indices must be integers

You extracted the dict key. 您提取了dict键。 Then, instead of using that to index the dict, you decided to iterate through the individual characters of the key itself. 然后,您决定不遍历键本身的各个字符,而不是使用该索引为dict编制索引。 Finally, you tried to use the individual letter as an index into the key, which is a simple string. 最后,您尝试使用单个字母作为键的索引,键是一个简单的字符串。

That's what the Python interpreter saw; 这就是Python解释器看到的。 it threw you an error message. 它引发了一条错误消息。 Instead, delete that innermost loop. 而是删除最里面的循环。 trips is the dict, and you use the extracted key to index it: trips是字典,您可以使用提取的键对其进行索引:

trips[trip] = float ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM