ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

YAML Key Value Extractor

YAML

Goal -- WPM

Ready
Exercise Algorithm Area
1import yaml
2
3def extract_yaml_key_values(data):
4"""Recursively extracts all key-value pairs from a YAML dictionary.
5
6Args:
7data: The YAML data structure (dictionary or other type).
8
9Returns:
10A list of tuples, where each tuple is a (key, value) pair.
11"""
12key_values = []
13if isinstance(data, dict):
14for key, value in data.items():
15if isinstance(value, dict):
16# Recursively extract from nested dictionaries
17key_values.extend(extract_yaml_key_values(value))
18else:
19# Add direct key-value pair
20key_values.append((key, value))
21# If data is not a dict, it cannot contain key-value pairs directly
22return key_values
23
24def process_yaml_for_pairs(yaml_string):
25"""Parses a YAML string and extracts all key-value pairs.
26
27Args:
28yaml_string (str): A string containing YAML data.
29
30Returns:
31A list of (key, value) tuples, or None if parsing fails.
32"""
33try:
34data = yaml.safe_load(yaml_string)
35if data is None:
36return [] # Return empty list for empty input
37
38# We only extract from dictionaries. If the root is not a dict, return empty.
39if not isinstance(data, dict):
40print("Warning: Root YAML element is not a dictionary. No key-value pairs to extract.")
41return []
42
43return extract_yaml_key_values(data)
44
45except yaml.YAMLError as e:
46print(f"Error parsing YAML: {e}")
47return None
48except Exception as e:
49print(f"An unexpected error occurred: {e}")
50return None
51
52# Example Usage:
53if __name__ == "__main__":
54nested_yaml = """
55config:
56server:
57host: localhost
58port: 8080
59database:
60type: postgresql
61connection_pool: 10
62credentials:
63user: admin
64pass: secret
65"""
66
67simple_yaml = """
68name: Example
69version: 1.0
70"""
71
72empty_yaml = ""
73
74non_dict_yaml = "- item1\n- item2"
75
76print("--- Extracting from nested YAML ---")
77pairs_nested = process_yaml_for_pairs(nested_yaml)
78if pairs_nested is not None:
79print(pairs_nested)
80
81print("\n--- Extracting from simple YAML ---")
82pairs_simple = process_yaml_for_pairs(simple_yaml)
83if pairs_simple is not None:
84print(pairs_simple)
85
86print("\n--- Extracting from empty YAML ---")
87pairs_empty = process_yaml_for_pairs(empty_yaml)
88if pairs_empty is not None:
89print(pairs_empty)
90
91print("\n--- Extracting from non-dictionary YAML ---")
92pairs_non_dict = process_yaml_for_pairs(non_dict_yaml)
93if pairs_non_dict is not None:
94print(pairs_non_dict)
Algorithm description viewbox

YAML Key Value Extractor

Algorithm description:

This algorithm traverses a YAML dictionary structure and extracts all direct key-value pairs. It handles nested dictionaries by recursively descending into them. The output is a flat list of tuples, where each tuple represents a key and its corresponding non-dictionary value. This is useful for flattening configuration data or extracting specific properties from complex YAML structures.

Algorithm explanation:

The `extract_yaml_key_values` function is a recursive helper. It iterates through the items of a dictionary. If a value is itself a dictionary, it calls itself recursively to extract pairs from that nested dictionary. Otherwise, if the value is not a dictionary (i.e., a scalar or a list), it appends the (key, value) tuple to the results list. The `process_yaml_for_pairs` function first parses the YAML string. It handles empty input by returning an empty list and checks if the root element is a dictionary, returning an empty list with a warning if not. It then calls the recursive helper. The time complexity is O(N), where N is the total number of nodes (keys and values) in the YAML structure, as each node is visited once. Space complexity is O(D + K), where D is the maximum depth of nesting and K is the total number of extracted key-value pairs. Edge cases include empty YAML input, non-dictionary root elements, and deeply nested structures.

Pseudocode:

Function extract_yaml_key_values(data):
  key_values = empty list
  If data is a dictionary:
    For each key, value in data:
      If value is a dictionary:
        Extend key_values with result of extract_yaml_key_values(value)
      Else:
        Append (key, value) to key_values
  Return key_values

Function process_yaml_for_pairs(yaml_string):
  Try:
    data = parse YAML yaml_string
    If data is None:
      Return empty list
    
    If data is not a dictionary:
      Print warning and return empty list

    Return extract_yaml_key_values(data)
  Catch YAML parsing error:
    Print error and return None
  Catch other errors:
    Print error and return None