0

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? :)

2 Answers 2

1

The data you get back is a list.

Change

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

to

txt = doc[0]["fields"]["domain"]
Sign up to request clarification or add additional context in comments.

1 Comment

You can print type(doc) to find out the type of data structure by the way. And if it's just simple built-ins, print doc is revealing enough to let you see how the data is nested.
1

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).

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.