Python Deep Destruction like JavaScript 和 assingment to new Object

问题描述

let newJson = {};

({
    "foo": {
        "name": newJson.FirstName,"height": newJson.RealHeight
    }
} =

{
    "foo": {
        "name": "Felipe","height": "55"
    }
});
console.log({newJson})

正如我们所知,上面的代码将在 JS 中返回以下输出

{newJson :{FirstName: "Felipe",RealHeight: "55"}}

我想知道在 PYTHON 中是否有一个 Lib 或一种方法

解决方法

在 Python 中搜索“解构赋值”会产生结果。

您可以使用 PEP 448 中定义的原生“元组解包”:

json_data = {
    "foo": {
        "name": "Felipe","height": "55"
    }
}

first_name,real_height = json_data["foo"]["name"],json_data["foo"]["height"]

print(first_name,real_height)
# Felipe 55

或者您可以使用基于 Python Data Model 的更接近的东西(灵感来自 this answer):

from operator import itemgetter

json_data = {
    "foo": {
        "name": "Felipe",real_height = itemgetter("name","height")(json_data["foo"])

print(first_name,real_height)
# Felipe 55