可以说我有两个列表,如下所示:
test_list = [[1,2],[4,5]]
lat_long_list = [(2.3,4.5),(5.6,7.8),(9.2,5.3),(8.9,9.0)]
我要将这两个列表转换为字典,如下所示:
test_dict = {vehicle 0:[
{1:{ lat: 2.3,
long:4.5,
key: 0
},
{2:{ lat:5.6,
long:7.8,
key: 1
}],
{vehicle 1:[
{4:{ lat: 9.2,
long:5.3,
key: 2
},
{5:{ lat:8.9,
long:9.0,
key: 3
}]
}
我该怎么做?
答案 0 :(得分:1)
我想test_list
将包含您的密钥,而lat_long_list
将包含您的值。
import pprint
test_list = [[1,2],[4,5]]
lat_long_list = [(2.3,4.5),(5.6,7.8),(9.2,5.3),(8.9,9.0)]
#Flatten your keys iterable
keys_list = itertools.chain.from_iterable(test_list)
print(keys_list)
>>> [1, 2, 4, 5]
result = dict([
(key, value) for key, value in zip(keys_list,lat_long_list)
])
print(result)
>>>{1: (2.3, 4.5), 2: (5.6, 7.8), 4: (9.2, 5.3), 5: (8.9, 9.0)}
您可能要检查:
答案 1 :(得分:1)
去那里:
test_list = [[1,2],[4,5]]
lat_long_list = [(2.3,4.5),(5.6,7.8),(9.2,5.3),(8.9,9.0)]
fields = ['lat','long','key']
test_dict = {}
ctr = 0
for i,l in enumerate(test_list):
test_dict['vehicle '+str(i)] = []
tempd = {}
for j,l2 in enumerate(l):
tempd[l2] = dict(zip(fields,list(lat_long_list[i+j+ctr])+[i+j+ctr]))
ctr+=1
test_dict['vehicle '+str(i)].append(tempd)
print(test_dict)
输出:
{'vehicle 0': [{1: {'lat': 2.3, 'long': 4.5, 'key': 0}, 2: {'lat': 5.6, 'long': 7.8, 'key': 1}}], 'vehicle 1': [{4: {'lat': 9.2, 'long': 5.3, 'key': 2}, 5: {'lat': 8.9, 'long': 9.0, 'key': 3}}]}
答案 2 :(得分:1)
嵌套字典和列表理解只是为了解决这个问题
d = {f"vehicle {num}": [{vehicle:{"lat":lat[0],"long":lat[1],"key":num*2+lat_num}}
for lat_num, (vehicle, lat) in enumerate(zip(item,lat_long_list[num*2:num*2+2]))]
for num, item in enumerate(test_list)}
print (d)
{'vehicle 0': [{1: {'lat': 2.3, 'long': 4.5, 'key': 0}},
{2: {'lat': 5.6, 'long': 7.8, 'key': 1}}],
'vehicle 1': [{4: {'lat': 9.2, 'long': 5.3, 'key': 2}},
{5: {'lat': 8.9, 'long': 9.0, 'key': 3}}]}