I am reading an excel file and using it to create a dictionary with which I am creating another dictionary using its key and value information. While doing so I have encountered a problem where I don't want single quotes in one of my values of the key literal_str which is a class name in my code and so I dont want it in single quotes. How can I remove the same from the output:
output_rules dictionary:
{'rules': {'VALID_CUSTOMER_ID': {'rule_type': 'REGEX', 'dimension': 'accuracy', 'params': {'pattern': '^[0-9]+$'}}}}
Issue
{'pattern': 'literal_str("^[0-9]+$")'}
Expected:
{'pattern': literal_str("^[0-9]+$")}
My code:
import openpyxl
import yaml
from yaml.representer import SafeRepresenter
class folded_str(str): pass
class literal_str(str): pass
class literal_unicode(str): pass
def change_style(style, representer):
def new_representer(dumper, data):
scalar = representer(dumper, data)
scalar.style = style
return scalar
return new_representer
class MyDumper(yaml.Dumper):
def increase_indent(self, flow=False, indentless=False):
return super(MyDumper, self).increase_indent(flow, False)
represent_literal_str = change_style('|', SafeRepresenter.represent_str)
yaml.add_representer(literal_str, represent_literal_str)
wb = openpyxl.load_workbook('C:\\Users\\Desktop\\config.xlsx')
ws = wb['rule']
final = {}
excel_read = {}
def iter_rows(active):
for row in active.iter_rows():
# data = [cell.value for cell in row]
# print(type(data))
yield [cell.value for cell in row]
res = iter_rows(ws)
keys = next(res)
for new in res:
excel_read = dict(zip(keys, new))
print(excel_read)
#Create rule for YAML
output_rules = {}
temp = {}
temp['pattern'] = excel_read['pattern']
output_rules = temp.copy()
temp.clear()
temp['params'] = {}
temp['params'] ['pattern'] = output_rules['pattern']
output_rules = temp.copy()
temp.clear()
temp = {
key: excel_read[key]
for key in ('rule_type', 'dimension')
}
output_rules = (temp | output_rules)
temp.clear()
# print("The output is:" ,output)
temp[excel_read['rules']] = output_rules
output_rules = temp.copy()
temp.clear()
temp['rules'] = output_rules
output_rules = temp.copy()
temp.clear()
print(literal_str.__name__)
str_rep = str(output_rules['rules'][excel_read['rules']]['params']['pattern'])
print(str_rep.replace(str_rep,f'literal_str("{str_rep}")'))
newstr = str_rep.replace(str_rep,f'{literal_str.__name__}("{str_rep}")')
output_rules['rules'][excel_read['rules']]['params']['pattern'] = newstr
print(output_rules)
output:
{'rules': {'VALID_CUSTOMER_ID': {'rule_type': 'REGEX', 'dimension': 'accuracy', 'params': {'pattern': 'literal_str("^[0-9]+$")'}}}}
Expected output:
{'rules':{'VALID_CUSTOMER_ID':{'rule_type': 'REGEX','dimension':'accuracy','params': {'pattern': literal_str('^[0-9]+$')}}}}