正在从嵌套字典中删除“\n”和“”

2024-10-02 02:41:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我的要求是发送从嵌套字典创建的JSON对象,该字典包含“\n”和“”等字符。下面是我想修改的字典

{'item': [{'Sno': 1,
'Item Code / Product Description': 'TGMOCL0015 / CORSAIR MOUSE, M55 RGB PRO, PART# CH-9308011-AP',
'HSN / SAC\nCode': '8471.60.60',
'Quantity': 7,
'Unit Price\n[INR]': 1741,
'Total\n[INR]': 12187,
'Rate': 18,
'IGST [INR]\nAmount': 2193.66,
'Line Total\n[INR]': 14380.66},
{'Sno': 2,
'Item Code / Product Description': 'TGMOCL0013 / CORSAIR MOUSE, HARPOON PRO-BLK-RGB, PART#CH-9301111-AP',
'HSN / SAC\nCode': '8471.60.60',
'Quantity': 8,
'Unit Price\n[INR]': 1200,
'Total\n[INR]': 9600,
'Rate': 18,
'IGST [INR]\nAmount': 1728.0,
'Line Total\n[INR]': 11328.0},
{'Sno': 3,
'Item Code / Product Description': 'TGCBCL0029 / CORSAIR CABINET SPEC-05, BLK - PART# CC-9011138-WW',
'HSN / SAC\nCode': '8473.30.99',
'Quantity': 37,
'Unit Price\n[INR]': 2225,
'Total\n[INR]': 82325,
'Rate': 18,
'IGST [INR]\nAmount': 14818.5,
'Line Total\n[INR]': 97143.5},
{'Sno': 4,
'Item Code / Product Description': 'TGHSCL0003 / CORSAIR GAMING HEADSET HS50 Stereo Carbon PART# CA-9011170-AP',
'HSN / SAC\nCode': '8518.30.00',
'Quantity': 92,
'Unit Price\n[INR]': 3000,
'Total\n[INR]': 276000,
'Rate': 18,
'IGST [INR]\nAmount': 49680.0,
'Line Total\n[INR]': 325680.0},
{'Sno': 5,
'Item Code / Product Description': 'TGMOCL0001 / CORSAIR MOUSE,HARPOON-BLK-RGB, PART#CH-9301011-AP',
'HSN / SAC\nCode': '8471.60.60',
'Quantity': 43,
'Unit Price\n[INR]': 1018,
'Total\n[INR]': 43774,
'Rate': 18,
'IGST [INR]\nAmount': 7879.32,
'Line Total\n[INR]': 51653.32},
{'Sno': 6,
'Item Code / Product Description': 'TGKBCL0001 / CORSAIR KEYBOARD K95 PLTN-BLK-MX Speed-RGB PART# CH-9127014-NA',
'HSN / SAC\nCode': '8471.60.40',
'Quantity': 8,
'Unit Price\n[INR]': 10750,
'Total\n[INR]': 86000,
'Rate': 18,
'IGST [INR]\nAmount': 15480.0,
'Line Total\n[INR]': 101480.0},
{'Sno': 7,
'Item Code / Product Description': 'TGKBCL0007 / CORSAIR KEYBOARD K55-BLK-RBRDME-RGB PART# CH-9206015-NA',
'HSN / SAC\nCode': '8471.60.40',
'Quantity': 14,
'Unit Price\n[INR]': 2400,
'Total\n[INR]': 33600,
'Rate': 18,
'IGST [INR]\nAmount': 6048.0,
'Line Total\n[INR]': 39648.0}]}

问题是我得到的钥匙如下:

'Item Code / Product Description'
'HSN / SAC\nCode'
'Unit Price\n[INR]'
'Total\n[INR]'
'IGST [INR]\nAmount'
'Line Total\n[INR]'

但应该是这样的:

'ItemCode/ProductDescription'
'HSN/SACCode'
'UnitPrice[INR]'
'Total[INR]'
'IGST[INR]Amount'
'LineTotal[INR]'

我尝试了以下代码,但不起作用:

res2 = {x: v.replace(' ','') 
    for x, v in res2.items()}
res2 = {x: v.replace('\n','') 
    for x, v in res2.items()}

错误如下:

 9 #key, value = list(res2.items())[0]
 10 res2 = {x: v.replace(' ','') 
---> 11 for x, v in res2.items()}
     12 res2 = {x: v.replace('\n','') 
     13 for x, v in res2.items()}





AttributeError: 'list' object has no attribute 'replace'

任何帮助都将不胜感激。抱歉,如果我在编辑时出错了


Tags: linecodeunitdescriptionproductitempricetotal
3条回答

您得到的具体错误是因为您不仅有字典,而且还有列表

通常,在处理嵌套结构时,最自然的拟合将是递归函数;大概是这样的:


def remove_key_whitespace(o):
  if isinstance(o, dict):
    return {
        k.replace('\n', '').replace(' ', ''): remove_key_whitespace(v)
        for k, v in o.items()
    }
  elif isinstance(o, list):
    return [remove_key_whitespace(item) for item in o]
  else:
    return o

另一种方法是将整个内容转换为字符串,用空格替换\n和空格,然后将其转换回dict

import ast
x = ast.literal_eval(str(x).replace('\\n','').replace(' ',''))
print(x['item'][0].keys())

dict_keys(['Sno', 'ItemCode/ProductDescription', 'HSN/SACCode', 'Quantity', 'UnitPrice[INR]', 'Total[INR]', 'Rate', 'IGST[INR]Amount', 'LineTotal[INR]'])

您可以通过以下方式重建整个系统:

n = {"item": []}
for i in d["item"]:
    n["item"].append({k.strip().replace("\n", ""): v for k, v in i.items()})

或一行:

{"item": [{k.strip().replace("\n", ""): v for k, v in i.items()} for i in d["item"]]}

其中d是您的数据结构

产量

print(json.dumps({"item": [{k.strip().replace("\n", ""): v for k, v in i.items()} for i in d["item"]]}, indent=4))
{
    "item": [
        {
            "Sno": 1,
            "Item Code / Product Description": "TGMOCL0015 / CORSAIR MOUSE, M55 RGB PRO, PART# CH-9308011-AP",
            "HSN / SACCode": "8471.60.60",
            "Quantity": 7,
            "Unit Price[INR]": 1741,
            "Total[INR]": 12187,
            "Rate": 18,
            "IGST [INR]Amount": 2193.66,
            "Line Total[INR]": 14380.66
        },
    ...

相关问题 更多 >

    热门问题