Skip to content

Instantly share code, notes, and snippets.

@womchik
Last active June 24, 2019 08:12
Show Gist options
  • Save womchik/58f5af5b7ffd69d202bfadecc07e69a3 to your computer and use it in GitHub Desktop.
Save womchik/58f5af5b7ffd69d202bfadecc07e69a3 to your computer and use it in GitHub Desktop.
my_dict
#!/usr/bin/env python3
from ruamel.yaml import YAML
from pathlib import Path
import re
my_dict = {}
path = Path('test.yml')
yaml = YAML(typ='safe')
data = yaml.load(path)
for insts in data:
for host in data[insts]:
first_group = host['groups'][0]
result = re.split(r'-', first_group, 1)
if result[0] not in my_dict:
my_dict.update({result[0]: {first_group: [host.get('name')]}})
else:
if first_group not in my_dict[result[0]]:
my_dict[result[0]].update({first_group: [host.get('name')]})
else:
my_dict[result[0]][first_group].append(host.get('name'))
print(f'{my_dict}')
---
inst_one:
- name: n1
addr: 127.0.0.1
groups:
- v1-int
- runner
- name: n2
addr: 127.0.0.1
groups:
- v2-int
- rabbit
- redis
inst_two:
- name: n3
addr: 127.0.0.1
groups:
- v1-prod
- runner
- name: n4
addr: 127.0.0.1
groups:
- v2-int
- rabbit
- redis
- name: n5
addr: 127.0.0.1
groups:
- v2-demo
- rabbit
- name: n6
addr: 127.0.0.1
groups:
- v2-demo
- rabbit
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment