python 列表去空值_python面试题之json去空值

前几天群里发了个面试题,做了一下。英语不好,代码写完了,才发现理解错了。在此特别的记录下这个小题。

大概意思就是,传入json,将value为null,[],{},""," "的这一条数据去掉,可以传入任意的json数据。

接下来看看我写的代码

import json

import time

z = """{

"first_ name": "Jane",

"last_ name": "Smith",

"email": "jane .smith@wyng.com",

"gender": null,

"invitations": [

{

"from": "",

"code": null

}

],

"company": {

"name": "",

"industries": {"dd":""},

"industries1": {"dd":"1"}

},

"address": {

"city": "New York",

"state": "NY",

"zip": "10011",

"street": " "

}

}"""

def isTrue(d):

z = [False," "]

if d not in z:

return d

def jsonToEmpty(l):

if type(l) == list:

ll = []

for i in l:

z = jsonToEmpty(i)

o = isTrue(z)

if o:

ll.append(z)

if ll:

return ll

elif type(l) == dict:

dd = {}

for k,v in l.items():

o = isTrue(v)

if o:

z = jsonToEmpty(o)

o = isTrue(z)

if o:

dd[k] = z

return dd

else:

o = isTrue(l)

if o:

return o

if __name__ == '__main__':

PP = json.loads(z)

p = jsonToEmpty(PP)

print(p)

代码水平有限,看群里别人写的也不错,记录了一下

info_dict = {

"first_ name": "Jane",

"last_ name": "Smith",

"email": "jane .smith@wyng.com",

"gender": "null",

"gender1": " ",

"gender2": "",

"invitations": [

{

"from": "",

"code": "null"

}

],

"company": {

"name": "",

"industries": []

},

"address": {

"city": "New York",

"state": "NY",

"zip": "10011",

"street": " "

}

}

def extraDictList(info):

if type(info) == dict:

re_info: dict = {}

for key, value in info.items():

if type(value) == dict or type(value) == list:

re = extraDictList(value)

if len(re) != 0:

re_info[key] = re

elif type(value) == str and value not in ["", " ", "null"]:

re_info[key] = value

return re_info

elif type(info) == list:

re_info: list = []

for value in info:

if type(value) == dict or type(value) == list:

re = extraDictList(value)

if len(re) != 0:

re_info.append(re)

else:

print("error list")

return re_info

else:

print("error")

if __name__ == '__main__':

re = extraDictList(info_dict)

print(re)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值