'Creating a YAML file for checking which userd_id belongs to which team?

Here is a sample yaml file:-

users.yaml

--- 
users: 
  - id: x
    name: Apurv
    team: Hockey
  - id: "y"
    name: Smriti
    team: Cricket
  - id: z
    name: Pankhuri
    team: Hockey
  - id: w
    name: Parth
    team: Cricket

Now I need to parse yaml to check if id == "y" then id 'y' is part of which team like here it is part of Cricket team and name is "Smriti"

I was writing a sample code as below:-

import yaml

with open("users.yml", 'r') as file:
    data = yaml.load(file, Loader=yaml.FullLoader)
    print(data)

Output:-

{'users': [{'id': 'x', 'name': 'Apurv', 'team': 'Hockey'}, {'id': 'y', 'name': 'Smriti', 'team': 'Cricket'}, {'id': 'z', 'name': 'Pankhuri', 'team': 'Hockey'}, {'id': 'w', 'name': 'Parth', 'team': 'Cricket'}]}

Can anybody suggests how I can parse the data to check the id corresponds to which team and name?



Solution 1:[1]

I think we can achieve the same as below:-

import yaml

with open("users.yml", 'r') as file:
    data = yaml.load(file, Loader=yaml.FullLoader)
    for k, v in data.items():
        for i in range(len(v)):
            if v[i]['id'] == 'y':
                name = v[i]['name']
                team = v[i]['team']
                print(name)
                print(team)

This has given me a result as:-

Smriti
Cricket

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 SMRITI MAHESHWARI