我有一个json
(使用qemu来宾代理),我将其转换为 python dictionary ,删除不需要的密钥,然后转发回json
;现在我发现的挑战是移除“键值”对,其中值本身是(:)
分开的。我在过滤后分享了一个示例dictionary
,
{'return': [{'ip-addresses': [{'ip-address': '127.0.0.1'}, {'ip-address': '::1'}], 'name': 'lo', 'hardware-address': '00:00:00:00:00:00'}, {'ip-addresses': [{'ip-address': '192.168.10.34'}, {'ip-address': 'fe80::5054:ff:feef:75fd'}], 'name': 'eth0', 'hardware-address': '52:52:00:ef:35:fd'}, {'name': 'eth1', 'hardware-address': '52:51:00:1d:37:dd'}]}
我想摆脱IPv6地址或任何值为(:)的ip-address密钥。 {"ip-address": "::1"}
。请帮助我提出想法/解决方案。
答案 0 :(得分:2)
def strip_ipv6(di):
remove = []
for k, v in di.items():
if isinstance(v, list):
for item in v:
strip_ipv6(item)
if isinstance(v, dict):
strip_ipv6(v)
if isinstance(v, str) and ':' in v and k.startswith('ip-address'):
remove.append(k)
for r in remove:
del di[k]