Home > Back-end >  How to get list out of string represented as ["Smth", "Smth", "Smth"]
How to get list out of string represented as ["Smth", "Smth", "Smth"]

Time:05-23

I have an pandas series object that includes features related to house. Those features are placed in squared brackets like this : ['Laundry In Unit', 'No Fee', 'Elevator'] but I need to have these features as a list of strings so I wonder if it possible.

Actually I want to create new column that will have "feature score" so I add points for different features. I tried to implement it like this(code below text) but this "feature" column appeared to have not lists but strings that look like lists.

features_dict = {
    'Laundry In Unit,':5 ,
    'No Fee,':5,
    'Elevator,': 3,
    'Dogs Allowed,':3,
    'Cats Allowed,': 3,
    'Swimming Pool,': 8,
    'Doorman,':9,
    'Fitness Center,': 8,
    'Dishwasher,': 5,
    'Hardwood Floors,': 4,
    'Pre-War,': 3,
    'Common Outdoor Space,': 4,
    'Private Outdoor Space,':8
}
features_list = clean_data['features'].tolist()
features_score = [0] * len(features_list)
for i in range(len(features_list)):
  for key, num in features_dict.items():
    for word in features_list[i].split(" "):
      if key == word:
        features_score[i] =num 

CodePudding user response:

if you have a string that reprs like this:

'["Smth", "Smth", "Smth"]'

and you want a list that looks like this:

["Smth", "Smth", "Smth"]

then you need ast.literal_eval:

import ast

the_string = '["Smth", "Smth", "Smth"]'

the_list = ast.literal_eval(the_string)
print(the_list)

output:

['Smth', 'Smth', 'Smth']

CodePudding user response:

maybe features_dict.keys() u will have a list of the key

Have a nice day

  • Related