Skip to content

Instantly share code, notes, and snippets.

@ycombinator
Created July 9, 2020 00:42
Show Gist options
  • Save ycombinator/c48af6ea6f121851c30b21d3de98c6c0 to your computer and use it in GitHub Desktop.
Save ycombinator/c48af6ea6f121851c30b21d3de98c6c0 to your computer and use it in GitHub Desktop.
Field aliasing
import yaml
def print_yaml(yaml_list):
print(yaml.safe_dump_all(yaml_list))
def make_yaml_list(tree):
yaml_list = []
for key in tree:
item = {
"name": key
}
if type(tree[key]) is dict:
item["type"] = "group"
item["fields"] = make_yaml_list(tree[key])
else:
item["type"] = "alias"
item["path"] = tree[key]
yaml_list.append(item)
return yaml_list
def tree_insert(tree, path, value):
if len(path) == 1:
leaf_key = path[0]
tree[leaf_key] = value
return
else:
head_key = path[0]
if not head_key in tree:
tree[head_key] = {}
tree = tree[head_key]
path.pop(0)
tree_insert(tree, path, value)
def make_tree(list):
tree = {}
for pair in list:
source = pair[0]
target = pair[1]
path = source.split(".")
tree_insert(tree, path, target)
return tree
def load_field_map():
# Expects local file ./field_map.tsv with format:
# source_field1_path target_field1_path
# source_field2_path target_field2_path
# ...
list = []
with open(r"./field_map.tsv") as f:
for line in f:
line = line.strip()
pair = line.split("\t")
list.append((pair[0], pair[1]))
return list
#
# Main
#
list = load_field_map()
tree = make_tree(list)
yaml_list = make_yaml_list(tree)
print_yaml(yaml_list)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment