Python链式JSON中具有列表元素的get()方法 [英] Python Chained get() Method With List Element inside JSON
问题描述
[Python 2.7]
[Python 2.7]
我有一个JSON源,它并不总是返回期望键的完整列表.我正在使用链接的gets()来解决这个问题.
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
我不能使用get()方法来解决这个问题,因为列表不支持get()属性:
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'
除了捕获数百个潜在的KeyError错误之外,还有一种更好的方法来解决潜在的['c']
缺失(类似于上面链接的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)?
推荐答案
我同意@stovfl的观点,即编写自己的查找函数是必经之路.虽然,我认为不需要递归实现.以下应该可以很好地工作:
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.
这篇关于Python链式JSON中具有列表元素的get()方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!