How to parse key=value pairs in Python

Parse a single line of key=value pairs separated by a delimiter into a Python dictionary.

Easy Python 3.9+ Aug 9, 2026 Strings & text 11 views 0 copies

Python code

15 lines
Python 3.9+
def parse_key_value_pairs(line: str, delimiter: str = "&") -> dict:
    """Parse a single line of key=value pairs into a dictionary."""
    pairs = {}
    for token in line.split(delimiter):
        if not token.strip():
            continue
        key, _, value = token.partition("=")
        pairs[key.strip()] = value.strip()
    return pairs


if __name__ == "__main__":
    line = "name=Alice&age=30&city=New York&active=true"
    result = parse_key_value_pairs(line)
    print(result)

Output

stdout
{'name': 'Alice', 'age': '30', 'city': 'New York', 'active': 'true'}

How it works

The split(delimiter) call breaks the input line into individual tokens. Each token is processed with partition("="), which splits the string into the key, the separator, and the value. Using partition instead of split is safer because it handles values that may contain the '=' character. The strip() calls clean up any whitespace around keys and values. Empty tokens are skipped with the continue statement.

Common mistakes

  • Using `split('=')` instead of `partition('=')` breaks values that contain '=' characters
  • Forgetting to skip empty tokens produces empty string values in the result
  • Not stripping whitespace leaves unexpected spaces in keys or values

Variations

  1. Use `urlparse` from the `urllib.parse` module if the input is part of a URL query string
  2. Use a dictionary comprehension with a conditional to filter empty tokens

Real-world use cases

  • Parsing query parameters from a URL string in a web handler before processing the request.
  • Reading configuration lines from a properties-style file where each line defines one setting.
  • Converting HTTP form-urlencoded body payloads into a structured dictionary for validation.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Strings & text

Related tutorials and quizzes for this topic.