如何在python中替换dict中的字符

2024-04-29 15:22:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我在字典里有这棵树:

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

如何用'{false}'替换0.0,用'{true}'替换1.0,并删除所有"。我找不到如何替换dict中的字符,而不是整个dict值。在字符串中很容易,我可以只做value = value.replace('1.0', 'True')value = value.replace('"', ''),但在dict中怎么做呢? 我将非常感谢任何帮助

编辑(这是生成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: []}

Tags: nametreeindexthresholdvaluetypecolumndict
2条回答

尝试从get go为您的树创建dict,而不是使用str.format()

这应该允许您迭代dict并替换不需要的值

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: []}

如何将dict转换为字符串,然后使用regex替换。然后,将其转换回字典

样本:

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)

相关问题 更多 >