Reputation: 1016
In this answer it was described how to edit specific entries of yaml files with python. I tried to use the code for the following yaml file
- fields: {domain: "www.mydomain.com", name: "www.mydomain.com"}
model: sites.site
pk: 1
but with
with open('my.yaml', 'r') as f:
doc = yaml.load(f)
txt = doc["fields"]["domain"]
print txt
I get the error
Traceback (most recent call last):
File "./test.py", line 9, in <module>
txt = doc["fields"]["domain"]
TypeError: list indices must be integers, not str
Now, I thought I could use keys on doc
.. Can somebody help me? :)
Upvotes: 0
Views: 1076
Reputation: 599450
You can use keys, but the fact that you've started your document with -
implies that it is a list. If you print doc
you will see this:
[{'fields': {'domain': 'www.mydomain.com', 'name': 'www.mydomain.com'},
'model': 'sites.site',
'pk': 1}]
that is, a list consisting of a single element, which is itself a dict. You could access it like this:
txt = doc[0]["fields"]["domain"]
or, if you're only ever going to have a single element, remove the initial -
(and the indents on the other lines).
Upvotes: 1
Reputation: 18237
The data you get back is a list.
Change
txt = doc["fields"]["domain"]
to
txt = doc[0]["fields"]["domain"]
Upvotes: 1