繁体   English   中英

如何从列表创建嵌套字典

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM