[英]Converting nested list and a list of tuples into a dictionary python
Lets say I have two lists as follows:假设我有两个列表如下:
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)]
I want to convert these two lists into a dictionary as follows:我想将这两个列表转换为字典,如下所示:
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
}]
}
How can i do this?我怎样才能做到这一点?
There you go:你有 go:
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)
Output: Output:
{'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}}]}
Nested dict and list comprehension just for the hell of it:嵌套的 dict 和列表理解只是为了它的地狱:
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}}]}
I guess test_list
will contain your keys, and lat_long_list
your values.我猜
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)}
You might want to check:您可能需要检查:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.