【问题标题】:Python named placeholders with nested dictionary (JSON)具有嵌套字典 (JSON) 的 Python 命名占位符
【发布时间】:2017-12-11 10:51:33
【问题描述】:

我正在使用格式和命名占位符并试图弄清楚: 如何在 Python 中使用命名占位符访问嵌套项(例如 JSON 对象)? 例如

data = {
    'first': 'John', 'last': 'Doe',
    'kids': {
        'first': 'number1',
        'second': 'number2',
        'third': 'number3'
    }
}  

'{first} {last} {kids}'.format(**data) # Python console
"John Doe {'second': 'number2', 'third': 'number3', 'first': 'number1'}"

但是我如何写我的“命名占位符格式”,以便我可以输出

 "John Doe, number1, number2, number3"

感谢任何有关如何从 JSON 对象获取输出的线索。

【问题讨论】:

    标签: python json nested format placeholder


    【解决方案1】:

    字符串格式支持索引;您不必引用键:

    '{first} {last}, {kids[first]}, {kids[second]}, {kids[third]}'.format(**data)
    

    演示:

    >>> '{first} {last}, {kids[first]}, {kids[second]}, {kids[third]}'.format(**data)
    'John Doe, number1, number2, number3'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-01-07
      • 2018-05-31
      • 2021-09-20
      • 2017-01-13
      • 2020-01-04
      • 2021-01-11
      • 2020-11-12
      相关资源
      最近更新 更多