簡體   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