为什么 python 对象被附加在列表的开头?

Why is python object being appended at beginning of list?

我有一个空字典,它将采用GeoJSON形式:

fleet_geojson = {"type": "FeatureCollection", "features": []}

我有一个 pandas 数据框每一行是space中的一个点:经纬度等信息

df_entire_fleet.to_csv('resources/entire_fleet.csv')

想用每个点的信息填充 GeoJSON 字典。因此,我这样做:

df_entire_fleet.apply(
    lambda row: addVehicle2Geojson(fleet_geojson, row['company_id'], row[
        'alarm'], row['battery_level'], row['id'], row['service_area_id'],
                                   row['staff_state'], row['location']),
    axis=1)

括号中的每个 字符串都是数据框中列的名称 函数:

def addVehicle2Geojson(fleet, comp, alarm, batt, id, serv_area, state,
                   coordinates):
fleet['features'].append({
    "type": "Feature",
    "properties": {
        'company_id': comp,
        'alarm': alarm,
        'battery_level': batt,
        'id': id,
        'service_area_id': serv_area,
        'staff_state': state,
    },
    "geometry": {
        "type": "Point",
        "coordinates": coordinates
    }
})

我得到无效的 GeoJSON,其中所有元素的顺序都颠倒了:

{
"features": [
    {
        "geometry": {
            "coordinates": "POINT(-0.00000 0.00000)",
            "type": "Point"
        },
        "properties": {
            "alarm": false,
            "battery_level": 83,
            "company_id": "xxxxxxxx",
            "id": "xxxxxxxx",
            "service_area_id": "xxxxxxxx",
            "staff_state": "xxxxxxxx"
        },
        "type": "Feature"
    },
    {
        "geometry": {
            "coordinates": "POINT(-0.00000 0.00000)",
            "type": "Point"
        },
        "properties": {
            "alarm": false,
            "battery_level": 1,
            "company_id": "xxxxxxxx",
            "id": "xxxxxxxx",
            "service_area_id": "xxxxxxxx",
            "staff_state": "xxxxxxxx"
        },
        "type": "Feature"
    }
],
"type": "FeatureCollection"

}

为什么 append() 改变键的顺序?

您使用的 python 是什么版本?

从 python 3.7 开始,字典中键的顺序被保留了下来,但在此之前 你不知道下次查看时键的顺序是什么他们.

因此,如果您确实需要保留键的顺序,请使用 OrderedDict,尽管您可能不需要使用 geojson :

def addVehicle2Geojson(fleet, comp, alarm, batt, id, serv_area, state, coordinates):
    fleet['features'].append(
        OrderedDict(type="Feature", properties={...}, geometry={...})
    )

参考:How to keep keys/values in same order as declared?