python列表get方法,Python链式JSON中具有列表元素的get()方法

[Python 2.7]

I have a JSON source that doesn't always return the full list of expected keys. I'm using chained gets() to address this.

d = {'a': {'b': 1}}

print(d.get('a', {}).get('b', 'NA'))

print(d.get('a', {}).get('c', 'NA'))

>>> 1

>>> NA

However, some dicts are in a list:

d = {'a': {'b': [{'c': 2}]}}

print(d['a']['b'][0]['c'])

>>> 2

I can't use a get() method to account for this because lists don't support the get() attribute:

d.get('a', {}).get('b', []).get('c', 'NA')

>>> AttributeError: 'list' object has no attribute 'get'

Beyond trapping the hundreds of potential KeyErrors, is there a preferred method to account for the potential missing ['c'] (in similar fashion to the chained get() construct above)?

解决方案

I agree with @stovfl that writing your own lookup function is the way to go. Although, I don't think a recursive implementation is necessary. The following should work well enough:

def nested_lookup(obj, keys, default='NA'):

current = obj

for key in keys:

current = current if isinstance(current, list) else [current]

try:

current = next(sub[key] for sub in current if key in sub)

except StopIteration:

return default

return current

d = {'a': {'b': [{'c': 2}, {'d': 3}]}}

print nested_lookup(d, ('a', 'b', 'c')) # 2

print nested_lookup(d, ('a', 'b', 'd')) # 3

print nested_lookup(d, ('a', 'c')) # NA

The class approach doesn't seem great because you're going to be creating a lot of unnecessary objects and if you're ever trying to lookup a node that isn't a leaf, then you're going to wind up with a custom object rather than the actual node object.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值