-
Notifications
You must be signed in to change notification settings - Fork 419
/
Copy pathecs_helpers.py
71 lines (52 loc) · 1.93 KB
/
ecs_helpers.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import yaml
from collections import OrderedDict
from copy import deepcopy
# Dictionary helpers
def dict_copy_keys_ordered(dict, copied_keys):
ordered_dict = OrderedDict()
for key in copied_keys:
if key in dict:
ordered_dict[key] = dict[key]
return ordered_dict
def dict_copy_existing_keys(source, destination, keys):
for key in keys:
if key in source:
destination[key] = source[key]
def dict_sorted_by_keys(dict, sort_keys):
if not isinstance(sort_keys, list):
sort_keys = [sort_keys]
tuples = []
for key in dict:
nested = dict[key]
sort_criteria = []
for sort_key in sort_keys:
sort_criteria.append(nested[sort_key])
sort_criteria.append(nested)
tuples.append(sort_criteria)
return list(map(lambda t: t[-1], sorted(tuples)))
def safe_merge_dicts(a, b):
"""Merges two dictionaries into one. If duplicate keys are detected a ValueError is raised."""
c = deepcopy(a)
for key in b:
if key not in c:
c[key] = b[key]
else:
raise ValueError('Duplicate key found when merging dictionaries: {0}'.format(key))
return c
def yaml_ordereddict(dumper, data):
# YAML representation of an OrderedDict will be like a dictionary, but
# respecting the order of the dictionary.
# Almost sure it's unndecessary with Python 3.
value = []
for item_key, item_value in data.items():
node_key = dumper.represent_data(item_key)
node_value = dumper.represent_data(item_value)
value.append((node_key, node_value))
return yaml.nodes.MappingNode(u'tag:yaml.org,2002:map', value)
yaml.add_representer(OrderedDict, yaml_ordereddict)
# File helpers
def yaml_dump(filename, data, preamble=None):
with open(filename, 'w') as outfile:
if preamble:
outfile.write(preamble)
yaml.dump(data, outfile, default_flow_style=False)