Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Turning string with embedded brackets into a dictionary

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'}
like image 702
mtmt Avatar asked May 28 '15 06:05

mtmt


People also ask

How do I turn a string into a dictionary?

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.

How do you convert a string representation to a dictionary in Python?

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.

Is {} a dictionary in Python?

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 (,).

Can you use {} in Python?

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.


2 Answers

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.

like image 122
vks Avatar answered Oct 22 '22 17:10

vks


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.

like image 37
Renatius Avatar answered Oct 22 '22 15:10

Renatius