Semicolon-separated String को Dictionary में Convert करना
यदि आपके पास इस तरह के Strings हैं:
"Name1=Value1;Name2=Value2;Name3=Value3"
और आप इसे Dictionary में Convert करना चाहते हैं, तो यह काफी आसान है। आप बस ';' पर Split कर सकते हैं और फिर '=' पर Split करके इसे Dict Constructor में Pass कर सकते हैं।
उदाहरण
>>> s = "Name1=Value1;Name2=Value2;Name3=Value3"
>>> dict(item.split("=") for item in s.split(";"))
{'Name2': 'Value2', 'Name3': 'Value3', 'Name1': 'Value1'}
Robust Version (Error Handling के साथ):
def parse_semicolon_dict(s, pair_sep=';', kv_sep='='):
"""Semicolon-separated Key=Value String को Dict में Parse करें"""
result = {}
for pair in s.split(pair_sep):
if not pair:
continue
parts = pair.split(kv_sep, 1) # केवल First Occurrence पर Split
if len(parts) == 2:
key, value = parts
result[key.strip()] = value.strip()
else:
# Handle Malformed Pairs
result[parts[0].strip()] = ''
return result
# Test
s = "Name1=Value1;Name2=Value2;Name3=Value3"
print(parse_semicolon_dict(s))
# {'Name1': 'Value1', 'Name2': 'Value2', 'Name3': 'Value3'}
# Edge Cases
print(parse_semicolon_dict("a=1;b=;=c;d")) # {'a': '1', 'b': '', '': 'c', 'd': ''}
URL Query String Parsing (urllib.parse):
from urllib.parse import parse_qs, parse_qsl
# parse_qs Returns Dict with List Values
parse_qs("name=John&age=30&city=NY")
# {'name': ['John'], 'age': ['30'], 'city': ['NY']}
# parse_qsl Returns List of Tuples
dict(parse_qsl("name=John&age=30&city=NY"))
# {'name': 'John', 'age': '30', 'city': 'NY'}