How to parse key=value pairs in Python
Parse a single line of key=value pairs separated by a delimiter into a Python dictionary.
Python code
15 linesdef 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
{'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
- Use `urlparse` from the `urllib.parse` module if the input is part of a URL query string
- 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
More from Strings & text
- Automatically Detect Weak Passwords from Large Password Lists in Python easy
- Build CSV row from Python list with proper quoting easy
- Build a Secure Password Strength Checker in Python easy
- Convert Natural Language Dates to Datetime in Python medium
- Count Characters, Words, and Lines in Python Text easy
- Extract Data from Strings in Python: Beginner's Guide easy
Keep learning
Related tutorials and quizzes for this topic.