我一直在尝试查看其他问题,但没有找到足以解决我问题的答案。如果字典包含许多键,我有一个列表,并且想返回仅包含这些键中的三个的字典列表。
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或filter,但我尝试了许多尝试都没有成功。
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})
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句