|
|
|
from collections import defaultdict |
|
import csv |
|
|
|
|
|
def create_hierarchy_dict(filename): |
|
""" |
|
Creates a dictionary where keys are nodes and values are sets of parent nodes representing the hierarchy of the ISCO-08 codes from the "unit" column of the isco_structure.csv file. |
|
|
|
Args: |
|
- filename: A string representing the path to the CSV file containing the ISCO-08 codes and their hierarchy. |
|
|
|
Returns: |
|
- A dictionary where keys are ISCO-08 unit codes and values are sets of their parent codes. |
|
""" |
|
isco_hierarchy = {} |
|
|
|
with open(filename, newline="") as csvfile: |
|
reader = csv.DictReader(csvfile) |
|
for row in reader: |
|
|
|
unit_code = row["unit"].zfill(4) |
|
|
|
parent_code = unit_code[:3] |
|
|
|
|
|
isco_hierarchy[unit_code] = {parent_code} |
|
|
|
|
|
|
|
major_code = unit_code[0] |
|
sub_major_code = unit_code[:2] |
|
isco_hierarchy[unit_code].update({major_code, sub_major_code}) |
|
|
|
return isco_hierarchy |
|
|
|
|
|
def create_hierarchy_tree(hierarchy_dict: dict) -> tuple: |
|
""" |
|
Builds the hierarchy tree and a mapping from name to ISCO code. |
|
|
|
Args: |
|
- hierarchy_dict: A dictionary representing the hierarchical structure. |
|
|
|
Returns: |
|
- tree: A dictionary representing the hierarchical structure. |
|
- code_to_node: A dictionary mapping from ISCO code to node name. |
|
""" |
|
|
|
tree = defaultdict(lambda: {"children": [], "parent": None}) |
|
code_to_node = {} |
|
|
|
def add_node(parent_code, node): |
|
code = node["name"].split("=")[0].strip() |
|
code_to_node[code] = node["name"] |
|
tree[code]["parent"] = parent_code |
|
if parent_code: |
|
tree[parent_code]["children"].append(code) |
|
for child in node.get("children", []): |
|
add_node(code, child) |
|
|
|
add_node(None, hierarchy_dict) |
|
return tree, code_to_node |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|