Home > Software engineering >  Define values in lists in multiple nested dictionaries in a list
Define values in lists in multiple nested dictionaries in a list

Time:05-15

I have a list consisting of multiple dict's, in them there are 2 keys of which one consists of a list consisting of multiple lists containing x and y coordinates.

MyList = [{dict0},{dict1},{dict2}...{dict2422}]

dict0{ 'geometry' { 'coordinates' : coordinates[[1,2],[3,4],[5,6]....]}, {type : 'Polygon'}, {'type' : 'Feature'} 

dict1{ 'geometry' { 'coordinates' : coordinates[[2,3],[7,1],[11,35]....]}, {type : 'Polygon'}, {'type' : 'Feature'}

The dict key 'coordinates' is a list size 1 containing a variable list size depending on which dict you access. Eg. key 'coordinates' contains a list size 1, which contains a list size 15 with each list containing x and y coordinates. Or it may contain 1 list of 96 lists, each 96 list containing 1 x and y coordinate each.

My goal is to get all x and y coordinates from each dictonary in MyList and group them together as one long list of x and y coordinates to plot. But I don't know how to extract them all from each list in each nested dictonary in each dictionary in MyList. So far I have done this.

for dict in features:
     for key, value in dict.items():
         if 'geometry' == key:
             for coordinate in value:
                if 'coordinates' in coordinate:

And after that I am unsure how to continue, or if I am even on the right path. Any help is great appreciated.

CodePudding user response:

I belive this is what you are looking for,

a=[]
b=[]
for dic in MyList:
    for i in range(len(dic["geometry"]["coordinates"])):
        a.append(dic["geometry"]["coordinates"][i][0])
        b.append(dic["geometry"]["coordinates"][i][1])

CodePudding user response:

Perhaps something like

coords = sum((item['geometry']['coordinates'] for item in MyList), start=[])

A "safe" version would be

coords = sum((x['coordinates'] for item in MyList if 'coordinates' in (x := item.get('geometry', {}))), start=[])

The standard idiom for transposing a list afterwards is

x, y = zip(*coords)
  • Related