从dict中删除空格:Python

时间:2012-10-31 06:44:08

标签: python dictionary

考虑一下我的口才。 实施例

 dict1 = {"1434": {"2012-10-29": {"275174": {"declaration_details":
 {"UTCC": `"38483 "`, "CNRE": "8334", "CASH": "55096.0"},
 "sales_details": {"UTCC": "38483.0", "CNRE": "8334.0", "CASH":
 "55098.0"}}, "275126": {"declaration_details": {"CNIS": "63371"},
 "sales_details": {"CNIS": "63371.0"}}, "275176":
 {"declaration_details": {"UTCC": "129909", "CASH": `"93200.0 "`,
 "CNRE": "28999", "PBGV": "1700"}, "sales_details": {"UTCC":
 "131619.0", "PBGV": "1700.0", "CASH": "92880.0", "CNRE": "28999.0"}},
 "275169": {"declaration_details": {"AMCC": "118616", "CNRE": "19462",
 "CASH": "120678.0"}, "sales_details": {"UTCC": "118616.0", "CNRE":
 "19462.0", "CASH": "120677.0"}}, "266741": {"declaration_details":
 {"UTCC": "42678", "CNRE": "4119", "CASH": `"24944.0 "`},
 "sales_details": {"UTCC": "42678.0", "CNRE": "4119.0", "CASH":
 "24944.0"}}}}}

我想删除该dict1中的所有空格。

哪种方法更好?

5 个答案:

答案 0 :(得分:6)

def removew(d):
  for k, v in d.iteritems():
    if isinstance(v, dict):
      removew(v)
    else:
      d[k]=v.strip()


removew(dict1)
print dict1

输出:

{'1434': {'2012-10-29': {'275174': {'declaration_details': {'UTCC': '38483', 'CNRE': '8334', 'CASH': '55096.0'}, 'sales_details': {'UTCC': '38483.0', 'CNRE': '8334.0', 'CASH': '55098.0'}}, '275126': {'declaration_details': {'CNIS': '63371'}, 'sales_details': {'CNIS': '63371.0'}}, '275176': {'declaration_details': {'UTCC': '129909', 'CNRE': '28999', 'CASH': '93200.0', 'PBGV': '1700'}, 'sales_details': {'UTCC': '131619.0', 'CNRE': '28999.0', 'CASH': '92880.0', 'PBGV': '1700.0'}}, '275169': {'declaration_details': {'CNRE': '19462', 'AMCC': '118616', 'CASH': '120678.0'}, 'sales_details': {'UTCC': '118616.0', 'CNRE': '19462.0', 'CASH': '120677.0'}}, '266741': {'declaration_details': {'UTCC': '42678', 'CNRE': '4119', 'CASH': '24944.0'}, 'sales_details': {'UTCC': '42678.0', 'CNRE': '4119.0', 'CASH': '24944.0'}}}}}

编辑: 正如Blckknght所指出的那样,如果你strip()包含空格的键(旧键,值对保留在dict中),第一个解决方案将会中断。如果你需要剥离使用dict理解,返回一个新的dict(从python 2.7开始可用)。

def removew(d):
    return   {k.strip():removew(v)
             if isinstance(v, dict)
             else v.strip()
             for k, v in d.iteritems()}
removew(dict1)

答案 1 :(得分:6)

我认为递归函数可能是您最好的方法。这样您就不必担心空格所在的嵌套字典的深度。

def strip_dict(d):
    return { key : strip_dict(value)
             if isinstance(value, dict)
             else value.strip()
             for key, value in d.items() }

如果除了值之外还要从键中删除空格,只需将key替换为字典理解的第一行中的key.strip()

答案 2 :(得分:2)

这是一个函数,它不仅会从值中删除空格,还会删除键。

它会在找到字典时递归,就像其他答案一样:

def strip_dict(d):
    """
    Recursively remove whitespace from keys and values in dictionary 'd'
    """

    for key, value in d.iteritems():
        if ' ' in key:
            d[key.strip()] = value
            del d[key]
        if isinstance(value, dict):
            strip_dict(value)
        elif isinstance(value, list):
            d[key.strip()] = [x.strip() for x in value]
        elif isinstance(value, str):
            d[key.strip()] = value.strip()

答案 3 :(得分:0)

我需要一个函数来清除包含其他dictslists或其他内容的嵌套字典中的所有空格。这应该会有所帮助,我使用了以上答案。

def strip_dict(d):
    def strip_list(l):
        return [strip_dict(x)
        if isinstance(x, dict)
        else strip_list(x)
        if isinstance(x, list)
        else clean(value) 
        for x in l]

    def clean(string):
        return ''.join(string.split())

    return { key.strip() : strip_dict(value)
             if isinstance(value, dict)
             else strip_list(value)
             if isinstance(value, list)
             else value
             if isinstance(value, bool)
             else clean(value)
             for key, value in d.items() }

答案 4 :(得分:0)

由于上述答案在正确的路径中,但是存在一些错误,并且没有考虑某些可能性,因此我发布了我的答案版本,该版本递归地去除了键和值。

def strip_dict_keys_values(d):
    def strip_list(l):
        return [strip_dict_keys_values(x)
                if isinstance(x, dict) else strip_list(x)
                if isinstance(x, list) else clean(x) for x in l]

    def clean(value):
        if isinstance(value, str):
            return value.strip()
        return value

    return {key.strip(): strip_dict_keys_values(value)
            if isinstance(value, dict) else strip_list(value)
            if isinstance(value, list) else clean(value)
            if value is None else clean(value)
            for key, value in d.items()}