[英]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?如何将
0.0
替换为'{false}'
和1.0
替换为'{true}'
并删除所有"
。我找不到如何替换 dict 中的字符而不是整个 dict 值。在字符串中很容易我可以只做value = value.replace('1.0', 'True')
或value = value.replace('"', '')
但如何在字典中做到这一点? 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: []}
How about converting the dict to a string then replace using regex
.如何将 dict 转换为字符串,然后使用
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)
Try creating a dict from the get-go for your tree, instead of using str.format()
尝试从一开始就为你的树创建一个字典,而不是使用
str.format()
This should allow you to iterate through your dict and replace the undesired values.这应该允许您遍历您的 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: []}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.