【问题标题】:Get only name of lists from YAML in Python仅从 Python 中的 YAML 获取列表名称
【发布时间】:2019-10-02 16:11:00
【问题描述】:

假设我有一个具有以下结构的 yaml 文件:

root:
  uncle:
  children:
    son:
      grandson:
        bob:
        charlie:
    daughter:
      granddaughter:
        tamara:
        julia:

我想要的只是显示孩子的后代,没有自己的后代。为了澄清,我只想显示:

son: 
daughter:

我写了以下代码sn-p:

import yaml

    with open('sample.yaml', 'r') as list:
        children_list = yaml.safe_load(list)
        print(children_list["root"]["children"])

但它打印了我所有的东西:

 children:
    son:
      grandson:
        bob:
        charlie:
    daughter:
      granddaughter:
        tamara:
        julia:

如何修复我的代码?

【问题讨论】:

  • 发布的输出不是您的代码产生的。

标签: python yaml


【解决方案1】:

如果我理解,那么您需要钥匙, 只需添加 children_list["root"]["children"].keys()

【讨论】:

    【解决方案2】:

    您可以通过准确描述要打印的内容来修复您的代码。首先,你的yaml 加载结构是

    {'root': {
        'uncle': None
        'children': {
            'son': {
                'grandson': {
                     'bob': None,
                     'charlie': None}},
            'daughter': {
                'granddaughter': {
                     'tamara': None,
                     'julia': None}}}}}
    

    这是一个嵌套的字典。您的代码要求输入 ['root']['children'],即结构

    {'son': {'grandson': {'bob': None, 'charlie': None}},
     'daughter': {'granddaughter': {'tamara': None, 'julia': None}}}
    

    如果你想要的只是标签(键),那么你需要从这个结构中提取这些键:

    for k in children_struct["root"]["children"].keys():
        print(k)
    

    这将打印标签——但没有尾随冒号,因为这是一个句法分隔符,不是存储结构的一部分。

    【讨论】:

      猜你喜欢
      • 2015-04-26
      • 2022-07-25
      • 2017-04-11
      • 1970-01-01
      • 1970-01-01
      • 2018-02-17
      • 2018-11-18
      • 2021-07-05
      • 2021-08-02
      相关资源
      最近更新 更多