0

我有一个嵌套结构,例如

target = \
{'A1':
   {'B1': 'a1b1',
    'B2': 'a1b2'
   }
{'A2':
   {'B1': 'a2b1',
    'B2': 'a2b2'
   }
}

我怎样才能轻松找到第二级(熊猫术语)中具有“B2”的所有项目,即['a1b2', 'a2b2']

我试过

glom(target, T[:, 'B2'])

glom(target, Path(Path(), Path('B2')))
4

1 回答 1

1

我假设您指定的目标是这样的字典 -

import glom
from glom import Coalesce, SKIP

target = \
{'A1':
   {'B1': 'a1b1',
    'B2': 'a1b2'
   },
'A2':
   {'B1': 'a2b1',
    'B2': 'a2b2'
   },
'A3':
   {'B1': 'a2b1',
   }
}

# We don't care about the outer key in the dictionary
# so we get only the inner dictionary by using values()

data = target.values()

# In the spec, we access the path "B2". 
# Coalesce allows us to skip the item if it does not contain "B2"

spec = [Coalesce("B2",default=SKIP)]

print(list(glom.glom(data,spec)))

# ['a1b2', 'a2b2']
于 2021-01-02T20:45:20.957 回答