Skip to content

Instantly share code, notes, and snippets.

@seanwiseman
Created June 1, 2020 09:46
Show Gist options
  • Select an option

  • Save seanwiseman/d2f40f7ea522f2cb2308077d6ab05537 to your computer and use it in GitHub Desktop.

Select an option

Save seanwiseman/d2f40f7ea522f2cb2308077d6ab05537 to your computer and use it in GitHub Desktop.
def extract_key_value_pairs(input_str, keys):
"""
# Example:
result = extract_key_value_pairs(
input_str="Postcode: NG11 Radius: 5 Price range: 450000-500000 Number of bedrooms: 2",
keys=["Postcode", "Radius", "Price range", "Number of bedrooms"]
)
>>> result
{'Number of bedrooms': '2', 'Radius': '5', 'Postcode': 'NG11', 'Price range': '450000-500000'}
"""
data = {}
for k in keys:
value = ""
char_index = input_str.find(k) + len(k) + 2
while True:
try:
char = input_str[char_index]
except IndexError:
break
if char == " ":
break
value += char
char_index += 1
data[k] = value
return data
result = extract_key_value_pairs(
input_str="Postcode: NG11 Radius: 5 Price range: 450000-500000 Number of bedrooms: 2",
keys=["Postcode", "Radius", "Price range", "Number of bedrooms"]
)
print(result)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment