删除dict中所有层次级别的特殊字符 - Python

时间:2018-03-07 08:38:11

标签: python json loops dictionary

我有一个像这样的python dict:

{
"stationlist": {
    "tunein": {
        "@base-m3u": "/sbin/tunein-station.m3u",
        "@base": "/sbin/tunein-station.pls",
        "@base-xspf": "/sbin/tunein-station.xspf"
    },
    "station": [
        {
            "@lc": "34753",
            "@br": "128",
            "@mt": "audio/mpeg",
            "@name": "Dance Wave Retro!",
            "@id": "1057402",
            "@genre": "Urban Contemporary"
        },
        {
            "@lc": "12847",
            "@br": "64",
            "@logo": "http://i.radionomy.com/document/radios/a/a265/a2654f5f-669e-4b9e-ac13-962971886ad2.jpg",
            "@mt": "audio/aacp",
            "@name": "COOLfahrenheit 93 - (7)",
            "@id": "1735956",
            "@ct": "25 Hours - #11D8'1 (Soft Version)",
            "@genre": "Easy Listening",
            "@genre2": "Pop"
        },
        ...
        ...

我需要从所有层次级别的dict中的所有键中删除@符号。

试过这个:Removing special characters from dictionary

productDictionary=dict(map(str.strip,x) for x in productDictionary.items())

没多大帮助。在此先感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

试试这个

def filter_dict(d):
    for key, value in d.items():
        if key.startswith('@'): 
            key = key[1:]
            del d["@"+key]
        if isinstance(value, dict):
            d[key] = filter_dict(value)
        elif isinstance(value, list):
            d[key] = [filter_dict(l) for l in value]
        else:
            d[key]=value
    return d

将字典传递给此函数,它将产生所需的输出,而不管层次结构如何。如果abc是您的字典,则filter_dict(abc)将以所需格式更新abc。请注意,abc将自动更新,因为字典是可变的。

示例代码

from pprint import pprint

abc = {
    "stationlist": {
        "tunein": {
            "@base-m3u": "/sbin/tunein-station.m3u",
            "@base": "/sbin/tunein-station.pls",
            "@base-xspf": "/sbin/tunein-station.xspf"
        },
        "station": [
            {
                "@lc": "34753",
                "@br": "128",
                "@mt": "audio/mpeg",
                "@name": "Dance Wave Retro!",
                "@id": "1057402",
                "@genre": "Urban Contemporary"
            },
            {
                "@lc": "12847",
                "@br": "64",
                "@logo": "http://i.radionomy.com/document/radios/a/a265/a2654f5f-669e-4b9e-ac13-962971886ad2.jpg",
                "@mt": "audio/aacp",
                "@name": "COOLfahrenheit 93 - (7)",
                "@id": "1735956",
                "@ct": "25 Hours - #11D8'1 (Soft Version)",
                "@genre": "Easy Listening",
                "@genre2": "Pop"
            },
        ]
     }
 }

def filter_dict(d):
    for key, value in d.items():
        if key.startswith('@'): 
            key = key[1:]
            del d["@"+key]
        if isinstance(value, dict):
            d[key] = filter_dict(value)
        elif isinstance(value, list):
            d[key] = [filter_dict(l) for l in value]
        else:
            d[key]=value
    return d


print "before"
pprint(abc)

filter_dict(abc)

print "after"
pprint(abc)

<强>输出

before
{'stationlist': {'station': [{'@br': '128',
                              '@genre': 'Urban Contemporary',
                              '@id': '1057402',
                              '@lc': '34753',
                              '@mt': 'audio/mpeg',
                              '@name': 'Dance Wave Retro!'},
                             {'@br': '64',
                              '@ct': "25 Hours - #11D8'1 (Soft Version)",
                              '@genre': 'Easy Listening',
                              '@genre2': 'Pop',
                              '@id': '1735956',
                              '@lc': '12847',
                              '@logo': 'http://i.radionomy.com/document/radios/a/a265/a2654f5f-669e-4b9e-ac13-962971886ad2.jpg',
                              '@mt': 'audio/aacp',
                              '@name': 'COOLfahrenheit 93 - (7)'}],
                 'tunein': {'@base': '/sbin/tunein-station.pls',
                            '@base-m3u': '/sbin/tunein-station.m3u',
                            '@base-xspf': '/sbin/tunein-station.xspf'}}}

after
{'stationlist': {'station': [{'br': '128',
                              'genre': 'Urban Contemporary',
                              'id': '1057402',
                              'lc': '34753',
                              'mt': 'audio/mpeg',
                              'name': 'Dance Wave Retro!'},
                             {'br': '64',
                              'ct': "25 Hours - #11D8'1 (Soft Version)",
                              'genre': 'Easy Listening',
                              'genre2': 'Pop',
                              'id': '1735956',
                              'lc': '12847',
                              'logo': 'http://i.radionomy.com/document/radios/a/a265/a2654f5f-669e-4b9e-ac13-962971886ad2.jpg',
                              'mt': 'audio/aacp',
                              'name': 'COOLfahrenheit 93 - (7)'}],
                 'tunein': {'base': '/sbin/tunein-station.pls',
                            'base-m3u': '/sbin/tunein-station.m3u',
                            'base-xspf': '/sbin/tunein-station.xspf'}}}