What's the best way to build a dictionary from a string like the one below:
"{key1 value1} {key2 value2} {key3 {value with spaces}}"
So the key is always a string with no spaces but the value is either a string or a string in curly brackets (it has spaces)?
How would you dict it into:
{'key1': 'value1', 'key2': 'value2', 'key3': 'value with spaces'}
To convert a Python string to a dictionary, use the json. loads() function. The json. loads() is a built-in Python function that converts a valid string to a dict.
To convert a string to dictionary, we have to ensure that the string contains a valid representation of dictionary. This can be done by eval() function. Abstract Syntax Tree (ast) module of Python has literal_eval() method which safely evaluates valid Python literal structure.
What is a Python dictionary? A dictionary is an unordered and mutable Python container that stores mappings of unique keys to values. Dictionaries are written with curly brackets ({}), including key-value pairs separated by commas (,).
In languages like C curly braces ( {} ) are used to create program blocks used in flow control. In Python, curly braces are used to define a data structure called a dictionary (a key/value mapping), while white space indentation is used to define program blocks.
import re
x="{key1 value1} {key2 value2} {key3 {value with spaces}}"
print dict(re.findall(r"\{(\S+)\s+\{*(.*?)\}+",x))
You can try this.
Output:
{'key3': 'value with spaces', 'key2': 'value2', 'key1': 'value1'}
Here with re.findall
we extract key
and its value
.re.findall
returns a list with tuples of all key,value pairs.Using dict
on list of tuples provides the final answer. Read more here.
I can´t make it more elegantly:
input = "{key1 value1} {key2 value2} {key3 {value with spaces}}"
x = input.split("} {") # creates list with keys and values
y = [i.split(" {") for i in y] # separates the list-values from keys
# create final list with separated keys and values, removing brackets
z = [[i.translate(None,"{").translate(None,"}").split() for i in j] for j in y]
fin = {}
for i in z:
fin[i[0][0]] = i[-1]
It´s very hacky, but it should do the job.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With