xml excape形成python字典

xml excape形成python字典,python,dictionary,lambda,Python,Dictionary,Lambda,我有一个字典列表,希望遍历这些键以转义xml字符。我需要找到包含需要xml转义的字符的字符串,更新它们并将它们添加回字典列表中 有两个键需要检查和更新“name”和“name1” 我的列表如下所示: list: [{'level1': 3, 'code1': u'7000', 'name1': u'Donations received in the field', 'code': u'6100', 'name': u'Per diem', 'level': 3, 'balance': 0.0,

我有一个字典列表,希望遍历这些键以转义xml字符。我需要找到包含需要xml转义的字符的字符串,更新它们并将它们添加回字典列表中

有两个键需要检查和更新“name”和“name1”

我的列表如下所示:

list: [{'level1': 3, 'code1': u'7000', 'name1': u'Donations received in the field', 'code': u'6100', 'name': u'Per diem', 'level': 3, 'balance': 0.0, 'balance1': -1986.9100000000001}, {'level1': 3, 'code1': u'7100', 'name1': u'Interest income', 'code': u'6101', 'name': u'Team living Expenses', 'level': 3, 'balance': 0.0, 'balance1': 0.0}, etc ... ] 
我的代码到目前为止,但是'key'变量返回一个整数,而'val'保存着这个键。。。(例如:“level1”)并且它从未进入reduce lambda

def get_lines(self,data):
    if data['form']['export_format'] == 'xls':
        for row in self.result_temp:
            for key,val in row.items():
                if key == 'name' or key == 'name1':
                    reduce(lambda s,r: s.replace(*r),
                        [('&', '&'),
                        ('<', '&lt;'),
                        ('>', '&gt;'),
                        ("'", '&#39;'),
                        ('"', '&quot;')],
                        self.result_temp[row][val])
    return self.result_temp
def get_行(自身、数据):
如果数据['form']['export_format']='xls':
对于self.result_temp中的行:
对于键,第行中的val.items():
如果键='name'或键='name1':
减小(λs,r:s.替换(*r),
[('&','&;'),
('', ''),
("'", '''),
('"', '"')],
自身结果(临时[行][val])
返回自我结果温度
如果可能,请使用(
不是由
cgi转义的。转义
):


顺便说一句,在问题的代码中,
reduce
的返回值不会返回到字典中。

在滚动您自己的工具之前,请查看这些工具,看看它们是否适合您的需要

from xml.sax.saxutils import escape

escape_string = """<escape "foo" & 'bar'>"""
extra_entities = {"'": "&#39;", '"': "&quot;"}
escape(escape_string, extra_entities)
从xml.sax.saxutils导入转义
转义字符串=“”
额外实体={“':”';“,”:“}
转义(转义字符串、额外实体)

您不需要迭代整个字典项。只需迭代
name
name1
键即可。谢谢@falsetru…您能举个例子吗?
def get_lines(self,data):
    if data['form']['export_format'] == 'xls':
        for row in self.result_temp:
            for key in ('name', 'name1'):
                if key not in row:
                    continue
                row[key] = cgi.escape(row[key])
    return self.result_temp
from xml.sax.saxutils import escape

escape_string = """<escape "foo" & 'bar'>"""
extra_entities = {"'": "&#39;", '"': "&quot;"}
escape(escape_string, extra_entities)