0

I'm a beginner in python and trying to pull data from yaml file to use in a python script, say my yaml file looks like this:

---
genre: horror
film:
 -name: conjuring
 -id: 1234
film:
 -name: halloween
 -id: 1222

How would I select each part of the yaml, for example say I want the id of the film with the name halloween using python? I managed to read the file in by writing this:

import yaml

with open("films.yaml", 'r') as stream:
    try:
        code = yaml.load(stream)
        print(code.each)
    except yaml.YAMLError as exc:
        print(exc)

but that only gives me the following output and doesn't display everything:

{'genre': 'horror', 'film': {'-name': 'halloween', '-id': 1222}}

Any help is appreciated.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
  • Dictionaries can't have duplicate keys. You can't have two `'film'` entries. – Peter Wood Sep 11 '18 at 20:26
  • @PeterWood ah ok, so what would be the best way to have multiple films defined in yaml? – user10349611 Sep 11 '18 at 20:29
  • Possible duplicate of [Getting duplicate keys in YAML using Python](https://stackoverflow.com/questions/44904290/getting-duplicate-keys-in-yaml-using-python) – Peter Wood Sep 12 '18 at 08:56
  • That makes this a different question really. I've marked it as a duplicate as a quick search revealed this: [Getting duplicate keys in YAML using Python](https://stackoverflow.com/questions/44904290/getting-duplicate-keys-in-yaml-using-python) – Peter Wood Sep 12 '18 at 08:57
  • ok cool, thanks for linking that and thanks for the help – user10349611 Sep 14 '18 at 13:58

2 Answers2

0

You can represent a list of films in yaml like this...

---
genre: horror
films:
- name: conjuring
  id: 1234
- name: halloween
  id: 1222
dekim
  • 622
  • 4
  • 6
0

As dekin notes, the problem is with your yaml syntax. You're providing duplicate entries for the key "film" rather than a list.

yaml lists should be of the format:

list_key:
    - item_1_field_1: foo
      item_1_field_2: bar
    - item_2_field_1: baz
      item_2_field_2: goof
robinsax
  • 1,195
  • 5
  • 9