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

Community
  • 1
  • 1
TheWaveLad
  • 966
  • 2
  • 14
  • 39

2 Answers2

1

The data you get back is a list.

Change

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

to

txt = doc[0]["fields"]["domain"]
huggie
  • 17,587
  • 27
  • 82
  • 139
  • 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. – huggie Dec 03 '14 at 09:16
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).

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895