从请求的正文中删除具有“无”值的键

时间:2018-11-15 23:13:57

标签: python python-requests

使用Python的$ anaconda search blpapi Using Anaconda API: https://api.anaconda.org Packages: Name | Version | Package Types | Platforms | Builds ------------------------- | ------ | --------------- | --------------- | ---------- conda-forge/blpapi | 3.9.2 | conda | linux-64, win-64, osx-64 | py36he980bc4_0, py36_blpapicpp3.8.18.1_1, py36_blpapicpp3.8.1.1_1, py27h2d50403_0, py27_blpapicpp3.8.18.1_1, py27hdc96acc_0, py36h2d50403_0, py27_blpapicpp3.8.1.1_1 : Python SDK for Bloomberg BLPAPI (<=3.9) dsm/blpapi | 3.9.0 | conda | linux-64, win-64 | py36_0, py27_0 josh/blpapi | 3.5.5 | conda | linux-64 | py27_0 macinv/blpapi | 3.9.0 | conda | linux-64, win-64 | py36_0, py27_0, py35_0, py34_0 mbonix/blpapi | 3.9.0 | conda | win-64 | py36_0 : Bloomberg's Open Market Data Initiative is part of the company's ongoing effort to foster open solutions for the financial services industry. p-vg/blpapi | 3.9.2 | conda | linux-64, win-64 | py36h6538335_0, py27hc56fc5f_0, py36hf484d3e_0, py27hf484d3e_0 : interface for Bloomberg API services using the Python programming language Found 6 packages Run 'anaconda show <USER/PACKAGE>' to get installation details 包,我有一个POST正文,其中包含一堆requests值,例如(字典,而不是JSON):

None

并且我希望发出的实际正文将所有值为{ 'name': 'John', 'surname': None, 'somelist': [ { 'a': 1, 'b': None }, { 'a': None, 'b': 2 } ], 'otherdict': { 'c': False, 'd': None } } 的条目都删除了,而不是转换为JSON None

null

{ 'name': 'John', 'somelist': [ { 'a': 1 }, { 'b': 2 } ], 'otherdict': { 'c': False } } 程序包是否可以执行此操作?我是否需要这样做?

1 个答案:

答案 0 :(得分:0)

您可以通过递归来做到这一点(删除具有None值的键,或者如果值不是clean则递归调用None方法):

def clean(d):
    if type(d) == list:
        return [clean(e) for e in d]
    elif type(d) == dict:
        for k, v in list(d.items()):
            if v is None:
                del d[k]
            else:
                d[k] = clean(v)
    return d

print(clean(data))

输出

{'somelist': [{'a': 1}, {'b': 2}], 'otherdict': {'c': False}, 'name': 'John'}