在 Python 中从字典中迭代并提取几个列表

Iterate and extract several lists from a dictionary in Python

我有这样一本字典:

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'

我想遍历字典以分别提取包含 'a1'、'a2'... 'a40' 的元素列表。像这样:

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

如何使用 Python 获取这些列表?

你可以使用类似这样的东西。使用 setdefault 使其动态化,并且 properties 中的任意数量的键都将包含在结果中。

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

输出

{'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]