首页 > 解决方案 > Python字典重构

问题描述

我正在构建一个 Flask REST API 来向 Google Places API 发出请求。

我的麻烦是以 Pythonic 方式处理嵌套的字典。

来自 Google Places 的(缩写)响应类似于:

[
  {
    "name": <string>,
    "opening_hours": { "open_now": <bool> },
    "photos": [{ "height": <string>, "width": <string>, "photo_reference": <string> }],
    "rating": <number>,
   }
]

我想将此 dict 重组为类似于:

[
  {
    "name": <string> OR '',
    "opening_hours": <bool> OR false,
    "photoSrc": <string> # (built from the h, w, and photo_reference keys),
    "rating": <number> OR None
  }
]

在 JavaScript 中,我通常会做一些事情,例如使用默认值进行嵌套解构或为功能组合创建辅助函数,例如pathOr(['path', 'to', 'key'], defaultValue)

我想知道其他人通常如何在他们的 Python API 中处理这样的事情。

提前十亿谢谢!

标签: pythonflask

解决方案


推荐阅读