Home > Back-end >  How to create a nested dictionary from lists
How to create a nested dictionary from lists

Time:09-23

I am trying to create a nested dictionary from 3 lists:

Input:

list1 = [a, b, c]
list2 = [d, e, f]
list3 = [1, 2, 3]

Desired 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'}]}

Any idees?

Thanks

CodePudding user response:

You can use zip with a list-comprehension to iterate through the fields in your lists.

For example:

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)]}

And this will be in the format you asked for, output is:

{'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}]}
  • Related