用 glom 切片级别
Slice level with glom
我有一个像
这样的嵌套结构
target = \
{'A1':
{'B1': 'a1b1',
'B2': 'a1b2'
}
{'A2':
{'B1': 'a2b1',
'B2': 'a2b2'
}
}
我如何轻松找到第二级(pandas 术语)中具有 'B2' 的所有项目,即 ['a1b2', 'a2b2']
?
我试过了
glom(target, T[:, 'B2'])
glom(target, Path(Path(), Path('B2')))
我假设你指定的目标是这样的字典 -
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']
我有一个像
这样的嵌套结构target = \
{'A1':
{'B1': 'a1b1',
'B2': 'a1b2'
}
{'A2':
{'B1': 'a2b1',
'B2': 'a2b2'
}
}
我如何轻松找到第二级(pandas 术语)中具有 'B2' 的所有项目,即 ['a1b2', 'a2b2']
?
我试过了
glom(target, T[:, 'B2'])
glom(target, Path(Path(), Path('B2')))
我假设你指定的目标是这样的字典 -
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']