首页 > 解决方案 > 用 .format 替换 dict 中存在的所有参数(所有字符串)

问题描述

I would like to know if there is any pythonic way of replacing all arguments (of all strings) that exist in a dictionary with .format. For example:

dictionary = {"name": "{name_user}", "age": 26, "infos": [ {"name": "{name_user}" }]}
information = {"name_user": "Joao"}

Different from the following:

dictionary["name"] = dictionary["name"].format(**information)
dictionary["infos"][0]["name"] = dictionary["infos"][0]["name"].format(**information)

I wonder if there is any more efficient way to do this.

Note: the dictionary would be a JSON file

标签: pythonpython-3.x

解决方案


这是另一种方法

information = {"name_user": "Joao"}
dictionary = {
     "name": information.get("name_user", ""), 
     "age": 26, 
     "infos": [ 
        {
          "name": information.get("name_user", "") 
        }]
}

我不知道这是否是最有效的方法,但我认为是更简单的方法。


推荐阅读