gpt4 book ai didi

python - 过滤字典以返回某些键

转载 作者:行者123 更新时间:2023-12-01 00:47:31 25 4
gpt4 key购买 nike

我一直在尝试查看其他问题,但没有找到足以解决我的问题的答案。我有一个包含许多键的字典列表,并且想要返回仅包含其中三个键的字典列表。

dict_keys(['dropoff_datetime', 'dropoff_latitude', 'dropoff_longitude', 'fare_amount', 'imp_surcharge', 'mta_tax', 'passenger_count', 'payment_type', 'pickup_datetime', 'pickup_latitude', 'pickup_longitude', 'rate_code', 'tip_amount', 'tolls_amount', 'total_amount', 'trip_distance', 'vendor_id'])

我编写了一个名为 parse_trips(trips) 的函数,该函数返回仅包含以下属性的行程列表:

trip_distance
pickup_latitude
pickup_longitude

我已经尝试了很多次迭代,并且很乐意使用 map 或过滤器,我已经尝试了很多变体但没有成功。

def parse_trips(trips):
new_list = []
for trip in trips:
return trips['trip_distance'], trips['pickup_latidude'], trips['pickup_longitude']

parsed_trips = parse_trips(trips)
parsed_trips and parsed_trips[0]

这是我想要得到的输出

# {'pickup_latitude': '40.64499',
# 'pickup_longitude': '-73.78115',
# 'trip_distance': '18.38'}

最佳答案

您可以通过字典理解创建包含所需键及其各自值的字典,并将其添加到 new_list

#List of keys you need
needed_keys = ['trip_distance', 'pickup_latitude', 'pickup_longitude']

#Iterate over trips list
for trip in trips:

#Create a dictionary with needed keys and their respective values and add it to result
new_list.append({k:trip[k] for k in needed_keys})

关于python - 过滤字典以返回某些键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56837878/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com