[英]How to create a nested dictionary from lists
我正在尝试从 3 个列表创建一个嵌套字典:
输入:
list1 = [a, b, c]
list2 = [d, e, f]
list3 = [1, 2, 3]
所需的 output:
{'type':'FeatureCollection', 'features': [
{'type':'Feature',
'geometry': {'type':'a',
'coordinates':'d'}
'id': '1'},
{'type':'Feature',
'geometry': {'type':'b',
'coordinates':'e'}
'id': '2'},
{'type':'Feature',
'geometry': {'type':'c',
'coordinates':'f'}
'id': '3'}]}
有什么想法吗?
谢谢
您可以使用zip
和列表理解来遍历列表中的字段。
例如:
list1 = ['a','b','c']
list2 = ['d','e','f']
list3 = [1, 2, 3]
features = {'type':'FeatureCollection', 'features':[{'type':'Feature', 'geometry':{'type':t, 'coordinates':c}, 'id':i} for t,c,i in zip(list1, list2, list3)]}
这将是您要求的格式,output 是:
{'type': 'FeatureCollection', 'features': [{'type': 'Feature', 'geometry': {'type': 'a', 'coordinates': 'd'}, 'id': 1}, {'type': 'Feature', 'geometry': {'type': 'b', 'coordinates': 'e'}, 'id': 2}, {'type': 'Feature', 'geometry': {'type': 'c', 'coordinates': 'f'}, 'id': 3}]}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.