首页 > 解决方案 > 如何用其他字典中存在的某些值替换字典中的占位符?

问题描述

我有一个名为 config 的字典:

配置:

{
  "label": "{{label}}",
  "order": "{{order}}",
  "visible": "{{is_visible}}",
  "items": "{{items}}"
}

价值观:

{
   "label": "Some text here!",
   "order": 23,
   "is_visible": True,
   "items": [1,2,3,4]
}

最终输出应该是:

输出:

{
  "label": "Some text here!",
  "order": 23,
  "visible": True,
  "items": [1,2,3,4]
}

注意:将无法使用 Jinja 库。因为它会将我输出中每个键的数据类型更改为字符串。

标签: pythonjsondictionarytemplatesjinja2

解决方案


如果您的键是恒定的,则可以update在 dict 上使用,在您的示例中它们是:

config={
  "label": "{{label}}",
  "order": "{{order}}",
  "visible": "{{is_visible}}",
  "items": "{{items}}"
}

values={
   "label": "Some text here!",
   "order": 23,
   "visible": True,
   "items": [1,2,3,4]
}

config.update(values)
config
{'label': 'Some text here!',
 'order': 23,
 'visible': True,
 'items': [1, 2, 3, 4]}

推荐阅读