TrailSurfer
TrailSurfer

Reputation: 169

Python yml config file

I am using python3 / version 3.6.9 and use a yml config file:

with open("config.yml", "r") as ymlfile:
    cfg = yaml.load(ymlfile)

for section in cfg:
    print(section)

Untill now i was only able to get this Output: BMW, Chevy, Mercedes

I want to loop through all elements of the config file and check the single values for Price, seats, year, that it's e.g. possible to filter the most seats, highest price.... individually. And it must be possible to extend the config file later without code change.

Thanks for every help

Cars:
      BMW:
            Price: 420
            Seats: 4
            Year: 2022
      Chevy:
            Price: 423
            Seats: 5
            Year: 1975
      Mercedes:
            Price: 424
            Seats: 6
            Year: 2000

Upvotes: 1

Views: 279

Answers (1)

Andrej Kesely
Andrej Kesely

Reputation: 195408

To get most seats, highest price from the Yaml you've provided in the question you can use (as long as the structure of Cars remains the same this script will work):

import yaml

with open("config.yml", "r") as ymlfile:
    cfg = yaml.safe_load(ymlfile)

most_seats = max(cfg["Cars"], key=lambda car: cfg["Cars"][car]["Seats"])
highest_price = max(cfg["Cars"], key=lambda car: cfg["Cars"][car]["Price"])
oldest = min(cfg["Cars"], key=lambda car: cfg["Cars"][car]["Year"])

print("Most seats =", most_seats)
print("Highest price =", highest_price)
print("Oldest =", oldest)
Most seats = Mercedes
Highest price = Mercedes
Newest = Chevy

Upvotes: 1

Related Questions