ga1996
ga1996

Reputation: 125

How do I replace a char in a dict in python

I have this tree in dictionary:

tree = {"'name': 'mass_index', 'direction': '>=', 'threshold': '27.8', 'children'": [0.0,
  {"'name': 'age', 'direction': '>=', 'threshold': '30.0', 'children'": [{"'name': 'mass_index', 'direction': '>=', 'threshold': '41.5', 'children'": [0.0,
      1.0]},
    1.0]}]}

type(tree)
dict

how can I replace 0.0 with '{false}' and 1.0 with '{true}' and remove all ". I couldn't find how to replace a char in dict and not the whole dict value. In a string is easy I can just do value = value.replace('1.0', 'True') or value = value.replace('"', '') but how can one do it in a dict? I would highly appreciate any help.

EDIT(this is the part that produces the dict):

feature_name = COLUMN_HEADERS[split_column]
    type_of_feature = FEATURE_TYPES[split_column]
    if type_of_feature == "continuous":
        question = "'cues': '{}', 'directions': '>=', 'thresholds': '{}', 'children'".format(feature_name, split_value)
        
    # feature is categorical
    else:
        question = "'cues': '{}', 'directions': '>=', 'thresholds': '{}', 'children'".format(feature_name, split_value)
    
    # instantiate sub-tree
    sub_tree = {question: []}

Upvotes: 0

Views: 120

Answers (2)

Rod Talingting
Rod Talingting

Reputation: 1080

How about converting the dict to a string then replace using regex. Then after, convert it back to a dictionary.

Sample:

import re
tree = {"'name': 'mass_index', 'direction': '>=', 'threshold': '27.8', 'children'": [0.0,
{"'name': 'age', 'direction': '>=', 'threshold': '30.0', 'children'": [{"'name': 'mass_index', 'direction': '>=', 'threshold': '41.5', 'children'": [0.0,
      1.0]},
    1.0]}]}

treeStr = str(tree)
    
treeStr = re.sub(r'\[0.0,', '[\'false\',', treeStr)
treeStr  = re.sub(r'\, 0.0]', ', \'false\']', treeStr)

treeStr = re.sub(r'\[1.0,', '[\'true\',', treeStr)
treeStr = re.sub(r'\, 1.0]', ', \'true\']', treeStr) 
    
import ast
treeDict = ast.literal_eval(treeStr)

type(treeDict)
print(treeDict)

Upvotes: 1

Dash
Dash

Reputation: 1299

Try creating a dict from the get-go for your tree, instead of using str.format()

This should allow you to iterate through your dict and replace the undesired values.

feature_name = COLUMN_HEADERS[split_column]
type_of_feature = FEATURE_TYPES[split_column]
question = {'directions': '>='}
if type_of_feature == "continuous":
    question['cues'] = feature_name
    question['thresholds'] = split_value

# I can't see any reason why this if statement is here, but I'll leave it if there's other things you add
else:   # feature is categorical
    question['cues'] = feature_name
    question['thresholds'] = split_value
    
    # instantiate sub-tree
sub_tree = {question: []}

Upvotes: 0

Related Questions