用重叠键合并dict

2024-09-28 03:12:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望通过组合其他3个GeoJSON dict对象来生成一个GeoJSON来返回。这三个条目具有相同的键,但值不同。比如像这样

d1 = {"type": "Feature",
      "geometry": {
        "type": "Point",
        "coordinates": [102.0, 0.5]
      },
      "properties": {
        "prop0": "value0"
      }
    }
d2 = {"type": "Feature",
      "geometry": {
        "type": "LineString",
        "coordinates": [
          [102.0, 0.0], [103.0, 1.0], [104.0, 0.0], [105.0, 1.0]
        ]
      },
      "properties": {
        "prop0": "value0",
        "prop1": 0.0
      }
    }
d3 =  {"type": "Feature",
      "geometry": {
        "type": "Polygon",
        "coordinates": [
          [
            [100.0, 0.0], [101.0, 0.0], [101.0, 1.0],
            [100.0, 1.0], [100.0, 0.0]
          ]
        ]
      },
      "properties": {
        "prop0": "value0",
        "prop1": { "this": "that" }
      }
    }

所需的输出如下

{
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "geometry": {
        "type": "Point",
        "coordinates": [102.0, 0.5]
      },
      "properties": {
        "prop0": "value0"
      }
    },
    {
      "type": "Feature",
      "geometry": {
        "type": "LineString",
        "coordinates": [
          [102.0, 0.0], [103.0, 1.0], [104.0, 0.0], [105.0, 1.0]
        ]
      },
      "properties": {
        "prop0": "value0",
        "prop1": 0.0
      }
    },
    {
      "type": "Feature",
      "geometry": {
        "type": "Polygon",
        "coordinates": [
          [
            [100.0, 0.0], [101.0, 0.0], [101.0, 1.0],
            [100.0, 1.0], [100.0, 0.0]
          ]
        ]
      },
      "properties": {
        "prop0": "value0",
        "prop1": { "this": "that" }
      }
    }
  ]
}

当我尝试使用像out.update(d1), out.update(d2)这样的方法时,键会重叠,因此不会追加所有3个字典


Tags: geojsontypepropertiesthisfeaturepointd2d1
2条回答

update根本不看值;它只涉及合并关键帧集。如果要合并现有键的,则需要自己进行合并

例如,您可能希望合并列表中的值:

merged = {}
for d in [d1, d2, d3]:
    for key in d:
        merged.setdefault(key, []).append(d[key])

或者,您可能希望对这些值求和:

merged = defaultdict(int)
for d in [d1, d2, d3]:
    for key in d:
        merged[key] += d[key]

等等。通常,您可以定义一个采用组合函数的函数:

from operator import add

def accumulate(x, y):
    if isinstance(x, list):
        return x + [y]
    else:
        return [x, y]

def merge(f, *dicts):
    m = {}
    for d in dicts:
        for key in d:
            if key not in m:
                m[key] = d[key]
            else:
                m[key] = f(m[key], d[key])
    return m

merged1 = merge(accumulate, d1, d2, d3)
merged2 = merge(operator.add, d1, d2, d3)

如果您需要为每个键使用不同的组合函数,您可以看到这会变得更加复杂,因此没有一种单一的内置方式来按值合并dict也就不足为奇了

由于误解了你的问题,我删除了以前的答案。在你做了编辑之后,我现在清楚了,你真正想要的只是把这些格言组合成一个列表。因此,这三条指令的代码只不过是:

dd = defaultdict(list)

featureNode = [d1,d2,d3]

dd['features'] = featureNode
dd['type'] = "FeatureCollection"

print(dd)

您将获得所需的输出

相关问题 更多 >

    热门问题