Dave0
Dave0

Reputation: 133

Load yaml file as dict

I have a YAML file that stores username and their ssh-keys.. it looks like this:

---
- bjones:
   name: Bob Jones
   ssh_keys:
   - "ssh-rsa dsgdsgds"
   - "ssh-rsa gdgsadg"
   - "ssh-rsa sagagsa"

- jsmith:
   name: Jimmy Smith
   ssh_keys:
   - "ssh-rsa gjdgjas"

I want to bring that into some python as a dict but not sure how.

In [98]: data = yaml.safe_load(open("/user-list.yaml"))
In [99]: type(data)
Out[99]: list

Where do I go from here to make this a dict?

I need the first user with multiple ssh-keys for the keys to be in a list on newlines as well

Upvotes: 1

Views: 861

Answers (1)

wim
wim

Reputation: 363536

The original markup is a list of dicts - but you can chain these dicts together:

>>> from collections import ChainMap
>>> result = ChainMap(*data)
>>> result["jsmith"]
{'name': 'Jimmy Smith', 'ssh_keys': ['ssh-rsa gjdgjas']}

If you're sure there are no duplicate entries in the original markup, i.e. len(data) == len(result), then you can safely convert it back into a single dict with dict(result).

Upvotes: 1

Related Questions