【问题标题】:Python: Flatten multiple nested dict and appendPython:展平多个嵌套的字典并追加
【发布时间】:2022-01-04 03:37:53
【问题描述】:

大家好, 我正在寻求帮助以尝试展平多个嵌套字典并将它们附加到新列表中。 我有多个字典,从这样的 geojson-File 加载:

data = json.load(open("xy.geojson"))

它们的结构都是这样的:

{'type': 'Feature', 'properties': {'tags': {'highway': 'cycleway', 'lit': 'yes', 'source': 'survey 08.2018 and Esri', 'surface': 'paving_stones', 'traffic_sign': 'DE:237 Radweg'}}, 'geometry': {'type': 'LineString', 'coordinates': [[6.7976974, 51.1935231], [6.7977131, 51.1935542], [6.7977735, 51.1935719], [6.7978679, 51.193578], [6.798005, 51.1936044], [6.7982118, 51.1936419], [6.7983474, 51.1936511], [6.7984899, 51.1936365], [6.7985761, 51.193623], [6.7986739, 51.1936186], [6.7987574, 51.1936188], [6.7988269, 51.1936342], [6.7988893, 51.1936529], [6.7989378, 51.1936778], [6.7990085, 51.1937739]]}}

现在我想展平字典的“标签”部分,所以我得到:

{'type': 'Feature', 'properties': {'highway': 'cycleway', 'lit': 'yes', 'source': 'survey 08.2018 and Esri', 'surface': 'paving_stones', 'traffic_sign': 'DE:237 Radweg'}, 'geometry': {'type': 'LineString', 'coordinates': [[6.7976974, 51.1935231], [6.7977131, 51.1935542], [6.7977735, 51.1935719], [6.7978679, 51.193578], [6.798005, 51.1936044], [6.7982118, 51.1936419], [6.7983474, 51.1936511], [6.7984899, 51.1936365], [6.7985761, 51.193623], [6.7986739, 51.1936186], [6.7987574, 51.1936188], [6.7988269, 51.1936342], [6.7988893, 51.1936529], [6.7989378, 51.1936778], [6.7990085, 51.1937739]]}}

到目前为止,我所做的是设置一个新列表并开始一个 for 循环:

filtered = []
for geo in data['features']:

但是如何在循环中展平 geo['properties']['tags'] 并将每个字典的结果附加到过滤中? 非常感谢大家,感谢大家的帮助! 克莱门斯

【问题讨论】:

    标签: python json dictionary geojson flatten


    【解决方案1】:

    可能有更好的方法,但这似乎可行:

    filtered = []
    for geo in data["features"]:
        updated = dict(**geo)
        updated["properties"] = geo["properties"]["tags"]
        filtered.append(updated)
    
    print(filtered)
    

    【讨论】:

    • 太棒了,非常感谢。 (您介意向我解释一下,dict(**geo) 是做什么的吗?)
    • 这会复制geo dict** 解包参数:docs.python.org/3/tutorial/…
    猜你喜欢
    • 1970-01-01
    • 2018-10-30
    • 2020-12-15
    • 1970-01-01
    • 2019-11-15
    • 2012-09-06
    • 2019-05-03
    • 2021-03-14
    • 2021-06-02
    相关资源
    最近更新 更多