简体   繁体   中英

Python3 - Convert a string to dict

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 :)

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'}

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

In case you don't have the variables defined as a string. You just have variables.

You can look into the following functions,

  • dir() will give you the list of in scope variables:
  • globals() will give you a dictionary of global variables
  • locals() will give you a dictionary of local variables

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)

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'}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM