Home > database >  Iterate and extract several lists from a dictionary in Python
Iterate and extract several lists from a dictionary in Python

Time:04-08

I have a dictionary like this:

dic = {'features': [{'type': 'Feature',
   'geometry': {'geodesic': False,
    'type': 'Point',
    'coordinates': [33.44904857310912, 52.340950190985474]},
   'id': '0',
   'properties': {'a1': 1.313, 
      'a2': -0.028, 'a3': 0.0026, 'a4': -0.025... 
      'a40': -0.056 ... 
   {'type': 'Feature',
   'geometry': {'geodesic': False,
    'type': 'Point',
    'coordinates': [33.817042613128294, 52.340950190985474]},
   'id': '1',
   'properties': {'a1': 1.319,
       'a2': -0.026, 'a3': 0.003,'a4': -0.045, ... 
       'a40': -0.032 ...... 

Almost 1000 ids, e.g. 'id': '0', 'id': '1'...'id': '960'

I want to iterate through the dictionary to extract a list of element containing 'a1', 'a2'... 'a40', separately. Something like this:

list_a1 = [1.313, 1.319... ]
list_a2 = [-0.028, -0.026 ...]

How to get these lists using Python?

CodePudding user response:

You can use something like this. Using setdefault makes it dynamic and any number of keys in properties will be included in the result.

dic = {'features': [{'type': 'Feature',
   'geometry': {'geodesic': False,
    'type': 'Point',
    'coordinates': [33.44904857310912, 52.340950190985474]},
   'id': '0',
   'properties': {'a1': 1.313,
    'a2': -0.028,
    'a3': 0.0026,
    'a4': -0.025,
    'a40': -0.056}},
  {'type': 'Feature',
   'geometry': {'geodesic': False,
    'type': 'Point',
    'coordinates': [33.817042613128294, 52.340950190985474]},
   'id': '1',
   'properties': {'a1': 1.319,
    'a2': -0.026,
    'a3': 0.003,
    'a4': -0.045,
    'a40': -0.032}}]}

separated_properties = {}
for feature in dic['features']:
    for key, val in feature['properties'].items():
        separated_properties.setdefault(key, []).append(val)

print(separated_properties)
print('a1: ', separated_properties['a1'])

Output

{'a1': [1.313, 1.319],
 'a2': [-0.028, -0.026],
 'a3': [0.0026, 0.003],
 'a4': [-0.025, -0.045],
 'a40': [-0.056, -0.032]}
a1:  [1.313, 1.319]
  • Related