Уровень среза с помощью glom
У меня есть вложенная структура вроде
target = \
{'A1':
{'B1': 'a1b1',
'B2': 'a1b2'
}
{'A2':
{'B1': 'a2b1',
'B2': 'a2b2'
}
}
как я могу легко найти все элементы, которые имеют 'B2' на втором уровне (терминология панд), т.е. ['a1b2', 'a2b2']
?
Я попытался
glom(target, T[:, 'B2'])
glom(target, Path(Path(), Path('B2')))
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']