Billy Rice
Billy Rice

Reputation: 67

How do I reference a specific entry in a YAML block using python?

I have some YAML data that looks like this:

people:
- name: "John"
  age: "20"
  family:
      - mother: "Alice"
        father: "Jeff"
        brother: "Tim"
        sister: "Enid"
- name: "Jake"
  age: "23"
  family:
      - mother: "Meg"
        father: "Rick"
        brother: "Carl"
        sister: "Maddy"

How do I print out the name of Jake's mother?

I'm really just trying to print out all family members for each person, but when I make a loop to go through each entry, the code views "name" "age" and "family" as strings.

My code looks like this:

(I have the yaml loaded as a dictionary "persons")

    for a in persons["people"]:
        if a == "family":
            for b in persons["people"][a]:
                print(b)

Upvotes: 0

Views: 110

Answers (2)

larsks
larsks

Reputation: 311606

people is a list of dictionaries. If you iterate over it with for a in persons["people"], then in each iteration of the loop, a will be a dictionary with the keys name, age, and family. You're looking for the entry where name is Jake, so:

for a in persons["people"]:
    if a["name"] == "Jake":
        ...

For reasons that are unclear from your question, family is a list of dictionaries, with only a single item in the list in each of your examples. You want the value of the key mother from this dictionary, which gets us:

for a in persons["people"]:
    if a["name"] == "Jake":
        mother_name = a["family"][0]["mother"]

If you have control over the format of the data, consider making family a single dictionary instead of a list of dictionaries:

people:
- name: "John"
  age: "20"
  family:
    mother: "Alice"
    father: "Jeff"
    brother: "Tim"
    sister: "Enid"
- name: "Jake"
  age: "23"
  family:
    mother: "Meg"
    father: "Rick"
    brother: "Carl"
    sister: "Maddy"

With that data structure, your code becomes:

for a in persons["people"]:
    if a["name"] == "Jake":
        mother_name = a["family"]["mother"]

Upvotes: 2

mamo
mamo

Reputation: 265

if __name__ == '__main__':
    with open('./file.yml') as file:
        people = yaml.full_load(file)
        for person in people["people"]:
            print(f"{person['name']} parents: ")
            family = person["family"][0]
            for role, name in family.items():
                print(role + ": " + name)

            print("")

The output will be

John parents: 
mother: Alice
father: Jeff
brother: Tim
sister: Enid

Jake parents: 
mother: Meg
father: Rick
brother: Carl
sister: Maddy

Upvotes: 0

Related Questions