4

考虑我有听写。前任。

 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 中的所有空格。

哪种方法更好?

4

5 回答 5

7
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(从 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)
于 2012-10-31T06:57:10.900 回答
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()

于 2012-10-31T06:58:31.853 回答
3

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

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

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()
于 2017-04-29T08:47:52.903 回答
1

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

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() }
于 2019-04-28T08:26:35.570 回答
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()}
于 2020-07-29T14:39:25.420 回答