Reputation: 1401
I have this string which I wish to convert to a dict:
class_="template_title" height="50" valign="bottom" width="535"
to basically change it to something like:
dict(class_='template_title', height='50', valign='bottom', width='535')
Nothing more complicated but I believe there is multiple steps in this problem. Would be nice if you could explain the solution or link to some documentation :)
Upvotes: 2
Views: 11234
Reputation: 239453
If you want to create a dictionary object from that string, you can use the dict
function and a generator expression which splits the string based on whitespaces and then by =
, like this
>>> data = 'class_="template_title" height="50" valign="bottom" width="535"'
>>> dict(item.split('=') for item in data.split())
{'width': '"535"', 'height': '"50"', 'valign': '"bottom"', 'class_': '"template_title"'}
This follows from the examples in this documentation section. So, if you pass an iterable which gives two elements on every iteration, then dict
can use that to create a dictionary object.
In this case, we first split the string based on whitespace characters with data.split()
and then we split every string based on =
, so that we will get key, value pairs.
Note: If you are sure that the data will not have "
character anywhere inside the string, then you can replace that first and then do the dictionary creation operation, like this
>>> dict(item.split('=') for item in data.replace('"', '').split())
{'width': '535', 'height': '50', 'valign': 'bottom', 'class_': 'template_title'}
Upvotes: 12
Reputation: 1002
In case you don't have the variables defined as a string. You just have variables.
You can look into the following functions,
These will give you the dictionary which you can manipulate, filter, all sort of things.
Something like this,
class_m="template_title"
height_m="50"
valign_m="bottom"
width_m="535"
allVars = locals()
myVars = {}
for key,val in allVars.items():
if key.endswith('_m'):
myVars[key] = val
print(myVars)
Upvotes: 0
Reputation: 27614
Look this way, View LIVE
ori = 'class_="template_title" height="50" valign="bottom" width="535"'
final = dict()
for item in ori.split():
pair = item.split('=')
final.update({pair[0]: pair[1][1:-1]})
print (final)
Output:
{'class_': 'template_title', 'valign': 'bottom', 'width': '535', 'height': '50'}
Upvotes: 0
Reputation: 10199
I'm not familiar with Python 3, so this may not be the most elegant solution, but this approach would work.
First split the string by spaces. list_of_records = string.split()
This returns a list that in your case would look like this:
['class_="template_title"', 'height="50"', 'valign="bottom"', 'width="535"']
Then iterate through the list and split each element by '='.
for pair in list_of_records:
key_val = pair.split('=')
key = pair[0]
val = pair[1]
Now in the body of the loop, just add it to the dictionary.
d[key] = val
Upvotes: 0