-2

Is it possible to parse lists in a yaml file directly into a python set by default ? If the answer is yes, how can I achieve this?

E.g.:

import yaml
from yaml.loader import SafeLoader

# Open the file and load the file
with open('Userdetails.yaml') as f:
    data = yaml.load(f, Loader=SafeLoader)
    print(data)

Expected Output:

{'User': {'user1', 'user2'}}

Instead of:

{'User': ['user1', 'user2']}

And without looping through the dictionary after load.

dl.meteo
  • 1,658
  • 15
  • 25
  • And what does `Userdetails.yaml` look like? Why are you using PyYAML, it only supports YAML 1.1, outdated in 2009. – Anthon Jul 20 '23 at 14:18
  • your expected output looks more like a dictionary than a set – scotscotmcc Jul 20 '23 at 14:19
  • 1
    You should be able to do something similar to https://stackoverflow.com/questions/36629559/how-to-use-custom-dictionary-class-while-loading-yaml by implementing a custom `Loader.construct_sequence`. – mkrieger1 Jul 20 '23 at 14:24
  • the yaml loader generates a Dictionary by default. set([user1,user2]) == {user1,user2} – dl.meteo Jul 20 '23 at 14:25
  • @mkrieger1 that goes into the right direction ! – dl.meteo Jul 20 '23 at 14:26

2 Answers2

0

If i right understand you, thats simple:

data = set(yaml.load(f, Loader=SafeLoader))
Firdaus
  • 53
  • 4
  • How does this create sets instead of lists? – mkrieger1 Jul 20 '23 at 14:20
  • No, I mean the list inside of a yaml should be parsed as a set instead of a list. And i know that i can loop through entries in the outcoming dict Checking the instance and run a type Casting. But this is not what i want to do. thanks for given a try. – dl.meteo Jul 20 '23 at 14:23
-1

What you provided as an example is not a set - it is a dict.

PyYAML parses data into dicts already - you should be pretty much good to go.

kehrazy
  • 1
  • 1