Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
292 views
in Technique[技术] by (71.8m points)

Converting text box input(html page) into a dictionary in flask(Python)

I am using html and flask. If a user enters a value with key in text box, how do I convert that into a dictionary?

Input :

'x':df['region'], 'y':df['age'], 'z': df['smoker']

Output:

{'x':df['region'], 'y':df['age'], 'z': df['smoker']}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you have it as string

query = "'x':df['region'], 'y':df['age'], 'z': df['smoker']"

then you could use eval() to convert it

data = eval("{" + query + "}")

Maybe it is not safe but it is fast and easy.

import pandas as pd

df = pd.DataFrame({
         'region': [1,2,3],
         'age':    [4,5,6],
         'smoker': [7,8,9],
         'other':  ['A','B','C'],
     })

query = "'x':df['region'], 'y':df['age'], 'z': df['smoker']"

data  = eval("{" + query + "}")

print(data)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...