【问题标题】:Edit yaml file with Python使用 Python 编辑 yaml 文件
【发布时间】:2015-01-31 18:12:49
【问题描述】:

answer 中,描述了如何使用 python 编辑 yaml 文件的特定条目。我尝试使用以下 yaml 文件的代码

 - fields: {domain: "www.mydomain.com", name: "www.mydomain.com"}
   model: sites.site
   pk: 1

但有

with open('my.yaml', 'r') as f:
    doc = yaml.load(f)
txt = doc["fields"]["domain"]
print txt

我得到了错误

Traceback (most recent call last):
  File "./test.py", line 9, in <module>
    txt = doc["fields"]["domain"]
TypeError: list indices must be integers, not str

现在,我想我可以在 doc.. 上使用密钥。有人可以帮助我吗? :)

【问题讨论】:

    标签: python


    【解决方案1】:

    你得到的数据是一个列表。

    改变

    txt = doc["fields"]["domain"]
    

    txt = doc[0]["fields"]["domain"]
    

    【讨论】:

    • 完美!谢谢你:)
    • 你可以print type(doc)顺便查一下数据结构的类型。如果它只是简单的内置插件,print doc 足以让您看到数据是如何嵌套的。
    【解决方案2】:

    您可以使用密钥,但您以- 开始文档这一事实意味着它是一个列表。如果您打印doc,您将看到:

    [{'fields': {'domain': 'www.mydomain.com', 'name': 'www.mydomain.com'},
      'model': 'sites.site',
      'pk': 1}]
    

    即由单个元素组成的列表,该元素本身就是一个字典。你可以这样访问它:

    txt = doc[0]["fields"]["domain"]
    

    或者,如果您只想拥有一个元素,请删除最初的 -(以及其他行的缩进)。

    【讨论】:

      猜你喜欢
      • 2015-06-13
      • 2020-12-14
      • 2018-12-19
      • 2021-07-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-25
      相关资源
      最近更新 更多