Load YAML as nested objects instead of dictionary in Python

前端 未结 3 776
没有蜡笔的小新
没有蜡笔的小新 2020-12-07 04:09

I have a configuration file in YAML that is currently loaded as a dictionary using yaml.safe_load. For convenience in writing my code, I\'d prefer to load it as a set of nes

3条回答
  •  独厮守ぢ
    2020-12-07 04:45

    Found a handy library to do exactly what I need: https://github.com/Infinidat/munch

    import yaml
    from munch import Munch
    mydict = yaml.safe_load("""
    a: 1
    b:
    - q: "foo"
      r: 99
      s: 98
    - x: "bar"
      y: 97
      z: 96
    c:
      d: 7
      e: 8
      f: [9,10,11]
    """)
    mymunch = Munch(mydict)
    

    (I had to write a simple method to recursively convert all subdicts into munches but now I can navigate my data with e.g.

    >>> mymunch.b.q
    "foo"
    

提交回复
热议问题