python 列表嵌套字典 添加修改删除_Python:如何从嵌套数据结构(列表和字典)中删除所有值?...

1586010002-jmsa.png

Here is some nested data, that includes lists, tuples, and dictionaries:

data1 = ( 501, (None, 999), None, (None), 504 )

data2 = { 1:601, 2:None, None:603, 'four':'sixty' }

data3 = OrderedDict( [(None, 401), (12, 402), (13, None), (14, data2)] )

data = [ [None, 22, tuple([None]), (None,None), None], ( (None, 202), {None:301, 32:302, 33:data1}, data3 ) ]

Goal: Remove any keys or values (from "data") that are None. If a list or dictionary contains a value, that is itself a list, tuple, or dictionary, then RECURSE, to remove NESTED Nones.

Desired output:

[[22, (), ()], ((202,), {32: 302, 33: (501, (999,), 504)}, OrderedDict([(12, 402), (14, {'four': 'sixty', 1: 601})]))]

Or more readably, here is formatted output:

StripNones(data)= list:

. [22, (), ()]

. tuple:

. . (202,)

. . {32: 302, 33: (501, (999,), 504)}

. . OrderedDict([(12, 402), (14, {'four': 'sixty', 1: 601})])

I will propose a possible answer, as I have not found an existing solution to this. I appreciate any alternatives, or pointers to pre-existing solutions.

EDIT

I forgot to mention that this has to work in Python 2.7. I can't use Python 3 at this time.

Though it IS worth posting Python 3 solutions, for others. So please indicate which python you are answering for.

解决方案

If you can assume that the __init__ methods of the various subclasses have the same signature as the typical base class:

def remove_none(obj):

if isinstance(obj, (list, tuple, set)):

return type(obj)(remove_none(x) for x in obj if x is not None)

elif isinstance(obj, dict):

return type(obj)((remove_none(k), remove_none(v))

for k, v in obj.items() if k is not None and v is not None)

else:

return obj

from collections import OrderedDict

data1 = ( 501, (None, 999), None, (None), 504 )

data2 = { 1:601, 2:None, None:603, 'four':'sixty' }

data3 = OrderedDict( [(None, 401), (12, 402), (13, None), (14, data2)] )

data = [ [None, 22, tuple([None]), (None,None), None], ( (None, 202), {None:301, 32:302, 33:data1}, data3 ) ]

print remove_none(data)

Note that this won't work with a defaultdict for example since the defaultdict takes and additional argument to __init__. To make it work with defaultdict would require another special case elif (before the one for regular dicts).

Also note that I've actually constructed new objects. I haven't modified the old ones. It would be possible to modify the old objects if you didn't need to support modifying immutable objects like tuple.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值