Python 2.7
我有一个JSON源代码,它并不总是返回预期键的完整列表。我使用链式gets()来解决这个问题。
d = {'a': {'b': 1}}
print(d.get('a', {}).get('b', 'NA'))
print(d.get('a', {}).get('c', 'NA'))
>>> 1
>>> NA然而,一些数据列在一个列表中:
d = {'a': {'b': [{'c': 2}]}}
print(d['a']['b'][0]['c'])
>>> 2我不能使用get()方法来解释这一点,因为列表不支持get()属性:
d.get('a', {}).get('b', []).get('c', 'NA')
>>> AttributeError: 'list' object has no attribute 'get'除了捕获数百个潜在的KeyErrors之外,是否有一种更好的方法来解释潜在的缺失['c'] (类似于上面的链式get()构造)?
发布于 2017-07-14 17:02:27
我同意@stovfl,编写自己的查找函数是可行的。尽管如此,我并不认为递归实现是必要的。以下几点应能发挥良好的作用:
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类方法似乎不太好,因为您将创建大量不必要的对象,如果您试图查找一个不是叶的节点,那么您将得到一个自定义对象,而不是实际的节点对象。
发布于 2017-07-14 16:36:49
问题:我不能用get()。因为列表不支持get()。
list.get():
类myGET(object):def __init__(self,data):if isinstance(data,dict):self.__dict__.update(data) if isinstance(data,list):self.__dict__.update(d) def get(self,key,default=None):if hasattr(self,(键):_attr = object.__getattribute__(self,key)如果isinstance( _attr,(list,dict)):返回myGET(_attr),否则:返回默认的d= {'a':{'b':{'c':2}} myGET(d).get('a',( {}).get('b',[]).get('c',' NA ') >>> 2 myGET(d).get('a',{}).get('b',[]).get('d','NA') >>> NA用Python测试的:3.4.2和2.7.9
https://stackoverflow.com/questions/45077397
复制相似问题