Consider i have dict. Ex.
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"}}}}}
i wanted to removed all white spaces in that dict1.
Which is the better way to do that?
def removew(d):
for k, v in d.iteritems():
if isinstance(v, dict):
removew(v)
else:
d[k]=v.strip()
removew(dict1)
print dict1
output:
{'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'}}}}}
EDIT:
As noted by Blckknght,the first solution, will break, if you strip()
keys that contain whitespace (old key,value pairs remain in the dict). If you need to strip both use dict comprehension, returning a new dict (available since 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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With